【发布时间】:2019-05-23 01:26:42
【问题描述】:
我们的 CLI 中有一个方法,它使用返回承诺的方法向用户打印消息。
exports.handler = (argv) => {
let customUtils = new Utils(argv);
Utils.deploy()
.then(res => console.log(`Ressource was deployed`))
.catch(e => {
console.error(`Ressource was not deployed`);
console.error(e);
process.exit(1);
});
}
我们正在寻找一种方法来测试控制台错误并在deploy() promise 被拒绝的情况下退出进程。
我们尝试使用沙盒存根,然后在异步测试中断言:
describe('when promise is errored', () => {
beforeEach(() => {
sandbox = sinon.createSandbox();
utilsStub = sandbox.stub(Utils.prototype, 'deploy').rejects('rejected');
processStub = sandbox.stub(process, 'exit');
consoleStub = sandbox.stub(console, 'error');
});
afterEach(() => {
sandbox.restore();
});
it('should call deploy and log the error before exiting', async () => {
await handler({});
expect(utilsStub).to.have.been.called;
expect(console.error).to.have.been.called;
});
});
此测试不起作用:AssertionError: expected error to have been called at least once, but it was never called。
当我们expect(process.exit).to.have.been.called; 时也会发生同样的情况。它从来没有被调用过。
我们以类似的方式成功测试了then 部分:
describe('when promise is resolved', () => {
beforeEach(() => {
sandbox = sinon.createSandbox();
utilsStub = sandbox.stub(Utils.prototype, 'deploy').callsFake(() => Promise.resolve('some text'));
consoleStub = sandbox.stub(console, 'log');
});
afterEach(() => {
sandbox.restore();
});
it('should call deploy and print success message', async () => {
await handler({});
expect(utilsStub).to.have.been.called;
expect(console.log).to.have.been.calledWith('Ressource was deployed');
});
});
【问题讨论】:
标签: javascript node.js chai sinon