我有一个类似于下面所示的测试。基本上我想测试一个特定的方法是否被延迟。
以下示例按预期工作,即调用 resolve 方法并通过测试:
it(`should delay execution by 1 second`, function () {
const clock = sandbox.useFakeTimers();
const p = new Promise(function (resolve) {
setTimeout(resolve, 1000);
});
clock.tick(1000);
return p;
});
但是,如果我将 setTimeout 包装在另一个 Promise 中,则 resolve 永远不会被调用:
it(`should delay execution by 1 second`, function () {
const clock = sandbox.useFakeTimers();
const p = Promise.resolve()
.then(() => {
return new Promise(function (resolve) {
setTimeout(resolve, 1000); // resolve never gets called
});
});
clock.tick(1000);
return p;
});
这里有什么问题?
我在 Node 6.9.5
上使用 Sinon 2.1.0
和 native promises。
最佳答案
问题似乎是您在超时开始之前计时 - 这是异步发生的,在 promise 回调中,在您的第二个代码段中。
这应该有效:
it(`should delay execution by 1 second`, function () {
const clock = sandbox.useFakeTimers();
return Promise.resolve().then(() => {
return new Promise(function (resolve) {
setTimeout(resolve, 1000);
clock.tick(1000); // resolve gets called now
});
});
});
关于javascript - 使用 Sinon 的假计时器时未触发 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048799/