【发布时间】: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