Search code examples
javascriptnode.jsmocha.jssinonsinon-chai

sinonjs : sinon stub not working on exported function


I am not able to stub the function functionToStub when I require it in controller file that I am writing mocha test for.

Here is an example of what I am trying to achieve

file1.js -- controller file

const functionUtil = require('./useFunc');

const newEndpoint = (req, res) => {

if(functionUtil.functionToStub()){
                    return "DID NOT STUB"
                }
                else{
                  return "DID STUB"
                }

}

useFunc.js

var functions = {
    functionToStub: functionToStub
}
function functionToStub (){
    return true
}

module.exports = functions;

mocha.js

const featureUtil = require('/useFunc')

   describe('When I call endpoint to stub', (done) => {
        var newStub;
        before(function(done) {

            newStub = sinon.stub(featureUtil, 'functionToStub')
            newStub.returns(false)

            chai.request(app.start())
            .post(`/api/testMyStub`)
            .send({'test':'testBody'})
            .end((err, res) => {
             console.log(res.body) // Expecting DID STUB to print here but the stub doesn't work, prints DID NOT STUB
             done();
            });
        });
        after(function(done) {
            newStub.restore();
            done();
        })
        it('should send an request', (done) => {
            expect(newStub).to.have.been.calledOnce
            done()

        }); 

    });

Solution

  • I was able to achieve it using proxyquire. I had to rewrite the function calls a little bit to get it to work. I am adding the updated test case :

    const featureUtil = require('/useFunc')
    var proxyquire =  require('proxyquire')
    
    isLegacyPrintingEnabledStub = sinon.stub(featureUtil, 'functionToStub')
    var isLegacyPrintingEnabledUtil = proxyquire('../../api/controllers/file1', {"featureUtil" : {'functionToStub': stubbedFunction }});
    stubbedFunction.returns(false)
    
    describe('When I call endpoint to stub', (done) => {
    
            before(function(done) {
    
                chai.request(app.start())
                .post(`/api/testMyStub`)
                .send({'test':'testBody'})
                .end((err, res) => {
                 console.log(res.body) // Logs DID STUB as expected
                 done();
                });
            });
            after(function(done) {
                newStub.restore();
                done();
            })
            it('should send an request', (done) => {
                expect(stubbedFunction).to.have.been.calledOnce
                done()
    
            }); 
    
        });
    
    

    After this I was able to see the code return DID STUB in the expected way.