【发布时间】:2019-04-30 22:48:46
【问题描述】:
我有一个异步函数f,它调用另一个异步函数g。为了测试f 是否调用g,我使用sinon 对g 进行存根,并断言它是使用should.js 调用的。
'use strict';
require('should-sinon');
const sinon = require('sinon');
class X {
async f(n) {
await this.g(n);
// this.g(n); // I forget to insert `await`!
}
async g(n) {
// Do something asynchronously
}
}
describe('f', () => {
it('should call g', async () => {
const x = new X();
sinon.stub(x, 'g').resolves();
await x.f(10);
x.g.should.be.calledWith(10);
});
});
但即使我在f 中调用g 时忘记使用await,此测试也通过了。
捕获此错误的方法之一是让存根返回一个虚拟承诺并检查其 then 是否被调用。
it('should call g', async () => {
const x = new X();
const dummyPromise = {
then: sinon.stub().yields()
};
sinon.stub(x, 'g').returns(dummyPromise);
await x.f(10);
x.g.should.be.calledWith(10);
dummyPromise.then.should.be.called();
});
但这有点麻烦。有什么方便的方法吗?
【问题讨论】:
-
should-sinon是否拉入sinon?大概你想require('sinon')之前require('should-sinon')?
标签: javascript node.js sinon should.js