Search code examples
javascriptnode.jsmocha.jssinon

Unit testing: how to stub a wrapper function


I'm new to unit testing and trying to figure out how to stub a wrapper function. I'm using Sinon/Mocha.

If I have a function like:

const user = await User.findOne({ email: email });

I've been able to stub it like so:

const userFindOneStub = sandbox.stub(User, 'findOne')
  .returns({
    _id: 'userId1234',
    companies: [
    {
      _id: 'companyId1234'
    }
  ]
});

But I've had to create a wrapper for my function to reorder the params for a specific function, using Lodash:

const userWrapper = _.rearg(UserFunction, [0, 1, 2, 3, 5, 4]);
const res = await userWrapper(someargs);

I can stub the UserFunction call, but how would I stub the userWrapper call in a unit test?


Solution

  • By save userWrapper as a module and follow Sinon How to Stub Dependency.

    For example you can create userWrapper.js to like this.

    // File: userWrapper.js
    // This is just sample
    const userWrapper = () => {
      // In your case is: _.rearg(UserFunction, [0, 1, 2, 3, 5, 4]);
      console.log('real');
    }
    module.exports = { userWrapper };
    

    Then you can use it in your main js to like this.

    // File: main.js
    const wrapper = require('./userWrapper.js');
    
    module.exports = async function main () {
      // In your case: const res = await userWrapper();
      wrapper.userWrapper();
    }
    

    And finally the test file.

    // File: test.js
    const sinon = require('sinon');
    const wrapper = require('./userWrapper.js');
    const main = require('./main.js');
    
    it('Stub userWrapper', () => {
      const stub = sinon.stub(wrapper, 'userWrapper').callsFake(() => {
        console.log('fake');
      });
    
      main();
    
      sinon.assert.calledOnce(stub);
    });
    

    When you run it using mocha from terminal:

    $ npx mocha test.js
    
    
    fake
      ✓ Stub userWrapper
    
      1 passing (3ms)