Search code examples
node.jsmocha.jssinonstub

Assert that the function passed into a stubbed function is the correct function


I'm trying to test my Node module using Mocha.

The module is very small here is an example...

import { sharedFunctionA, sharedFunctionB, commonFunction } from <file>

const functionA = token => _data => sharedFunctionA(token);
const functionB = () => data => sharedFunctionB(data);

exports.doThingA = token => {
  commonFunction(functionA(token));
};

exports.doThingB = () => {
  commonFunction(functionB());
};

This is only a brief example but it shows what I'm trying to do.

I need to test that doThingA and doThingB pass in the correct function to the commonFunction.

I have stubbed the commonFunction and I can see that it is being called but I can't assert that the function passed in is correct.

TBH... I'm beginning to think of restructuring this entirely to pass in some sort of enum to the commonFunction and running the respective function from there.


Solution

  • In this case you can stub on the sharedFunctionA and sharedFunctionB and then retrieve the argument of your stub on the commonFunction and call it. Then check your other stubs are being called with the desired arguments.

    I know it's tedious but it is the only way I can think of with your code.

    Quick example:

    const assert = require('assert')
    const sinon = require('sinon')
    const sharedFunctions = require('<fileWithSharedFunctions>')
    const commonStub = sinon.stub(sharedFunctions, 'commonFunction')
    const sharedBStub = sinon.stub(sharedFunctions, 'sharedFunctionB')
    
    const fileToTest = require('<fileToTest>')
    
    fileToTest.doThingB()
    commonStub.getCall(0).args[0]()
    assert(sharedBStub.calledOnce)