Hug*_*ães 2 javascript settimeout node.js promise sinon
我有一个类似于下面显示的测试.基本上我想测试特定方法是否会延迟.
以下示例按预期工作,即调用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;
});
Run Code Online (Sandbox Code Playgroud)
但是,如果我将setTimeout包装在另一个Promise中,则决不会调用该解析:
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;
});
Run Code Online (Sandbox Code Playgroud)
这有什么问题?
我正在使用Sinon 2.1.0和本地的承诺Node 6.9.5.
Ber*_*rgi 11
问题似乎是你在超时开始之前滴答作响 - 这是在你的第二个片段中的一个承诺回调中异步发生的.
这应该工作:
it(`should delay execution by 1 second`, function () {
const clock = sandbox.useFakeTimers();
return Promise.resolve().then(() => {
return new Promise(function (resolve) {
setTimeout(resolve, 1000); // resolve never gets called
clock.tick(1000);
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2835 次 |
| 最近记录: |