Sinon:暂存类的静态方法无法按预期方式工作

时间:2018-10-14 13:32:37

标签: javascript class testing static sinon

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

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 是否使用给定参数调用响应

describe('ProfileController', () => {

    let responseStub;

    beforeEach(function() {

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

但是尽管嘲笑了 response ,但ProfileController仍然调用了响应的实际实现(请参阅控制台输出:“我在这里。不愿意”

    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
    });

1 个答案:

答案 0 :(得分:0)

您需要先使用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然后使用该功能的存根版本,即可对其进行检查。