我正在使用chai-as-promised测试一些承诺。 我的问题是,我不确定如何在单个测试中有多个expect语句。 为了使expect().to.be.fulfilled
正常工作,我需要像这样返回它:
我使用chai-as-promised测试承诺,但不确定如何在一个测试中有多个expect语句。为了使expect().to.be.fulfilled
正常工作,需要将其返回。
it('test', () => {
return expect(promise).to.be.fulfilled
}
...或者使用notify
,像这样:
it('test', (done) => {
expect(promise).to.be.fulfilled.notify(done)
}
当我需要检查另一件事情,比如某个函数是否被调用时,就会出现问题,代码如下:
it('test', (done) => {
var promise = doSomething()
expect(sinon_function_spy.callCount).to.equal(1)
expect(promise).to.be.fulfilled.notify(done)
})
这里的问题在于,由于doSomething()
是异步的,当我调用expect
时,调用sinon_function_spy
可能还没有发生,导致测试不可靠。如果我使用then
,像这样:
it('test', (done) => {
var promise = doSomething()
promise.then(() => {
expect(sinon_function_spy.callCount).to.equal(1)
})
expect(promise).to.be.fulfilled.notify(done)
})
在这种情况下,测试技术上会按预期成功或失败,但它会失败,因为承诺被拒绝,由于then
调用中抛出了异常。同样,如果我有一个期望承诺被拒绝的情况:
it('test', (done) => {
var promise = doSomething()
promise.then(() => {
expect(sinon_function_spy.callCount).to.equal(1)
})
expect(promise).to.be.rejected.notify(done)
})
因为 promise 被拒绝并且没有调用 then,所以对 sinon_function_spy 的检查从未被调用。
我怎样才能可靠地执行并返回正确值的两个 expect 语句?