node.jsmockingsinonstubbingproxyquire

Stub a function inside a function without passing it as an argument


I have the following code:

const {compose} = require('./compose');


const complicatedFunction = async function (argA, argB) {
    const result = await getValue(argA)
    const value = await getValue2(argB)
    const composition = compose(result, value)
    validator(composition)
    return composition

I am calling the complicatedFunction to test the "validator" function. To test the validator function, I must stub the compose function to make it return whatever I want.

It would be easy to stub it and pass it as an argument, but it is not an option. How can stub compose to make it return any value? I know that proxyquire allows to mock dependencies but I don't understand how could I insert it in that situation


Solution

  • Try:

    complicatedFunction.js:

    const { compose } = require('./compose');
    
    const complicatedFunction = (argA, argB) => {
      const result = 1;
      const value = 2;
      const composition = compose(result, value);
      return composition;
    };
    
    module.exports = complicatedFunction;
    

    compose.js:

    module.exports = {
      compose() {},
    };
    

    complicatedFunction.test.js:

    const proxyquire = require('proxyquire');
    const sinon = require('sinon');
    
    describe('75761657', () => {
      it('should pass', () => {
        const composeStub = sinon.stub().withArgs(1, 2).returns(100);
        const complicatedFunction = proxyquire('./complicatedFunction', {
          './compose': {
            compose: composeStub,
          },
        });
        const actual = complicatedFunction();
        sinon.assert.match(actual, 100);
      });
    });