sinonjs:sinon 存根无法处理导出函数

sinonjs : sinon stub not working on exported function

当我 require 函数 functionToStub 在我正在为其编写 mocha 测试的控制器文件中时,我无法对函数 functionToStub 进行存根。

这是我想要实现的目标的示例

file1.js -- 控制器文件

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

        }); 

    });

我能够使用 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()

        }); 

    });

在此之后,我能够以预期的方式看到代码 return DID STUB

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

有箭头功能,可以正常使用