【问题标题】:Sinon: Stubbing static method of class does not work as expectedSinon:类的存根静态方法无法按预期工作
【发布时间】:2018-10-14 13:32:37
【问题描述】:

我想模拟以下类,用作另一个类的依赖项:

module.exports = class ResponseHandler {

static response(res, status_, data_, codes_) {
    console.log('Im here. Unwillingly');
    // doing stuff here...
};

ResponseHandler 由 ProfileController 导入并在那里使用:

const response = require('../functions/tools/response.js').response;

module.exports = class ProfileController {

static async activateAccountByVerificationCode(req, res) {
    try{
        // doing stuff here
        return response(res, status.ERROR, null, errorCodes);
    }
}

现在我正在为 ProfileController 编写单元测试,我正在测试 activateAccountByVerificationCode 是否使用给定的参数调用 response

describe('ProfileController', () => {

    let responseStub;

    beforeEach(function() {

        responseStub = sinon.stub(ResponseHandler, 'response').callsFake(() => null);
    });

但尽管 response 被模拟,ProfileController 仍然调用响应的真正实现(参见控制台输出:'Im here. Unwillingly'

    it('should respond accordingly if real verification code does not fit with the one passed by the user', async function () {
        // here you can still see that real implementation is still called
        // because of console output 'I'm here unwillingly'
        await controller.activateAccountByVerificationCode(req, res);

        console.log(responseStub.called); // -> false
        expect(responseStub.calledWith(res, status.ERROR, null, [codes.INVALID_VERIFICATION_CODE])).to.eql(true); // -> negative
    });

【问题讨论】:

    标签: javascript class testing static sinon


    【解决方案1】:

    您需要先使用 proxyquire 之类的库模拟控制器依赖项,然后在测试中使用此模拟实例。否则,您仍将使用原始(未存根)实现。

    const proxyquire = require('proxyquire');
    
    describe('ProfileController', () => {
    
        let responseStub;
        let Controller;
    
        beforeEach(function() {
    
            responseStub = sinon.stub(ResponseHandler, 'response').callsFake(() => null);
            Controller = proxyquire('./ProfileController', {'../functions/tools/response':responseStub})
        });
    
        it('should respond accordingly if real verification code does not fit with the one passed by the user', async function () {
            // here you can still see that real implementation is still called
            // because of console output 'I'm here unwillingly'
            await Controller.activateAccountByVerificationCode(req, res);
    
            console.log(responseStub.called); // -> false
            expect(responseStub.calledWith(res, status.ERROR, null, [codes.INVALID_VERIFICATION_CODE])).to.eql(true); // -> negative
        });
    

    Controller 然后使用你的函数的存根版本并且可以被检查。

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多