Home > Software engineering >  Proxyquire not overriding exported function
Proxyquire not overriding exported function

Time:10-29

I have a class modules/handler.js, which looks like this:

const {getCompany} = require('./helper');

module.exports = class Handler {
    constructor () {...}
    async init(){
        await getCompany(){
        ...
    }
}

it imports the function getCompany from the file modules/helper.js:

exports.getCompany = async () => {
 // async calls
}

Now in an integration test, I want to stub the getCompany method, and it should just return a mockCompany. However, proxyquire is not stubbing the method getCompany, instead the real ones gets called. The test:

const sinon = require('sinon');
const proxyquire = require("proxyquire");
const Handler = require('../modules/handler');

describe('...', () => {

    const getCompanyStub = sinon.stub();
    getCompanyStub.resolves({...});

    const test = proxyquire('../modules/handler.js'), {
      getCompany: getCompanyStub
    });

    it('...', async () => {
        const handler = new Handler();
        await handler.init(); // <- calls real method 
        ... 
    });
});

I've also tried it out without the sinon.stub where proxyquire returns a function directly returning an object, however, this also did not work.

I would be very thankful for every pointer. Thanks.

CodePudding user response:

The Handler class you are using is required by the require function rather than proxyquire.

handler.js:

const { getCompany } = require('./helper');

module.exports = class Handler {
  async init() {
    await getCompany();
  }
};

helper.js:

exports.getCompany = async () => {
  // async calls
};

handler.test.js:

const sinon = require('sinon');
const proxyquire = require('proxyquire');

describe('69759888', () => {
  it('should pass', async () => {
    const getCompanyStub = sinon.stub().resolves({});
    const Handler = proxyquire('./handler', {
      './helper': {
        getCompany: getCompanyStub,
      },
    });
    const handler = new Handler();
    await handler.init();
  });
});

test result:

  69759888
    ✓ should pass (2478ms)


  1 passing (2s)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |                   
 handler.js |     100 |      100 |     100 |     100 |                   
 helper.js  |     100 |      100 |     100 |     100 |                   
------------|---------|----------|---------|---------|-------------------
  • Related