用Sinon模拟所需的模块

问题描述 投票:0回答:1

我正在为后端Express服务器测试控制器,正在努力对所需模块进行存根和/或监视。

这是我的控制器的示例:

const logger = require('../../middleware/logger');

module.exports.verify = (req, res) => {
    const log = logger(req, __filename);

    controller.verify(req.query.code, (err, response) => {
        log('Verifying query code.');
        // ...

        // error
        log.error(e, 'There was an error.');
    });
};

[在测试中,我想确保使用指定的参数调用了loglog.error方法。我已经通过使用proxyquire并取消了功能而成功完成了[[some,但是我不确定如何进行监视。

const controller = proxyquire( '../../middleware/logger`: sinon.stub().callsFake(() => (() => {})); );
node.js sinon
1个回答
0
投票
这里是解决方法:

index.js

const logger = require("./logger"); const controller = require("./controller"); module.exports.verify = (req, res) => { const log = logger(req, __filename); controller.verify(req.query.code, (err, response) => { log("Verifying query code."); log.error(err, "There was an error."); }); };

logger.js

module.exports = function logger(req, filename) { function log(message) { console.log(message); } log.error = function error(error, message) { console.error(message); }; return log; };

controller.js

module.exports = { verify(code, callback) { callback(); }, };

index.spec.js

const proxyquire = require("proxyquire"); const sinon = require("sinon"); const controller = require("./controller"); describe("verify", () => { let sandbox; before(() => { sandbox = sinon.createSandbox(); }); it("should verify correctly", () => { const logErrorStub = sandbox.stub(); const logStub = sandbox.stub(); logStub.error = logErrorStub; const loggerStub = sandbox.stub().callsFake(() => logStub); const { verify } = proxyquire("./", { "./logger": loggerStub, }); const controllerVerifyStub = sandbox.stub(controller, "verify"); const mReq = { query: { code: 123 } }; const mRes = {}; const mError = new Error("verify error"); verify(mReq, mRes); controllerVerifyStub.yield(mError, null); sandbox.assert.calledWith(controllerVerifyStub, 123, sandbox.match.func); sandbox.assert.calledWith(loggerStub, mReq, sinon.match.string); sandbox.assert.calledWith(logStub, "Verifying query code."); sandbox.assert.calledWith(logErrorStub, mError, "There was an error."); }); });

带有覆盖率报告的单元测试结果:

verify ✓ should verify correctly (57ms) 1 passing (62ms) ---------------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | ---------------|----------|----------|----------|----------|-------------------| All files | 86.49 | 100 | 60 | 86.11 | | controller.js | 50 | 100 | 0 | 50 | 3 | index.js | 100 | 100 | 100 | 100 | | index.spec.js | 100 | 100 | 100 | 100 | | logger.js | 20 | 100 | 0 | 20 | 3,5,6,8 | ---------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57808949
© www.soinside.com 2019 - 2024. All rights reserved.