断言失败,因为它不等待承诺解决
Assertion fails as it does not wait for promise resolution
我使用 mocha、sinon 和 chai 来 运行 一组测试。这是我正在测试的方法
fn.method().then(function(response) {
console.log(response)
test()
})
我已经把 method
像这样删掉了
test = sinon.spy()
fn = { method: sinon.stub().resolves("hello") }
在我的测试中我有
expect(fn.method()).to.have.been.called
console.log("goodbye")
expect(test).to.have.been.called
我希望测试通过并按顺序打印 "hello" 和 "goodbye" 但我看到的是 expect(test).to.have.been.called
失败而且我还看到 "hello" 得到在 "goodbye".
之后打印
测试 test
在 promise 解析后调用的正确方法是什么?
它失败了,因为(大概)在 sinon .resolves
钩子中有足够的异步性,你的两行
console.log("goodbye");
expect(test).to.have.been.called;
运行 在您测试的方法 运行 的 .then
块中的代码之前。 (我们知道它是 运行ning 因为我们看到正在记录控制台,但我们知道它必须是 运行ning after 第二行 expect
.)
我会从它的期望中解开你存根的方法,可能是这样的:
// in test.js
fn.method().then(() => {
expect(test).to.have.been.called;
});
我使用 mocha、sinon 和 chai 来 运行 一组测试。这是我正在测试的方法
fn.method().then(function(response) {
console.log(response)
test()
})
我已经把 method
像这样删掉了
test = sinon.spy()
fn = { method: sinon.stub().resolves("hello") }
在我的测试中我有
expect(fn.method()).to.have.been.called
console.log("goodbye")
expect(test).to.have.been.called
我希望测试通过并按顺序打印 "hello" 和 "goodbye" 但我看到的是 expect(test).to.have.been.called
失败而且我还看到 "hello" 得到在 "goodbye".
测试 test
在 promise 解析后调用的正确方法是什么?
它失败了,因为(大概)在 sinon .resolves
钩子中有足够的异步性,你的两行
console.log("goodbye");
expect(test).to.have.been.called;
运行 在您测试的方法 运行 的 .then
块中的代码之前。 (我们知道它是 运行ning 因为我们看到正在记录控制台,但我们知道它必须是 运行ning after 第二行 expect
.)
我会从它的期望中解开你存根的方法,可能是这样的:
// in test.js
fn.method().then(() => {
expect(test).to.have.been.called;
});