sinonjs:sinon存根在导出的函数上不起作用

时间:2020-03-26 17:13:35

标签: javascript node.js mocha sinon sinon-chai

functionToStub函数require在要为其编写摩卡测试的控制器文件中时,我无法对函数const functionUtil = require('./useFunc'); const newEndpoint = (req, res) => { if(functionUtil.functionToStub()){ return "DID NOT STUB" } else{ return "DID STUB" } } 进行存根处理。

这是我要实现的目标的一个例子

file1.js-控制器文件

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

module.exports = functions;

useFunc.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()

        }); 

    });

mocha.js

<button type="button" class="btn btn-primary" data-toggle="modal" 
    data-target="#myModal" data-table="1">Button 1</button>
<button type="button" class="btn btn-primary" data-toggle="modal" 
    data-target="#myModal" data-table="2">Button 2</button>
<button type="button" class="btn btn-primary" data-toggle="modal" 
    data-target="#myModal" data-table="3">Button 3</button>

2 个答案:

答案 0 :(得分:0)

我能够使用proxyquire实现它。我不得不重写一些函数调用才能使其正常工作。我正在添加更新的测试用例:

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()

        }); 

    });

此后,我能够以预期的方式看到代码返回DID STUB

答案 1 :(得分:0)

对我来说更简单的方法: 当我想为 stub export function()... 时,我遇到了同样的问题。它不起作用。 所以我将 export function() 转换为使用箭头函数:export const nameFunction = ()...

带箭头功能,正常工作。