我有一个类似于下图所示的测试。基本上我想测试特定方法是否被延迟。
以下示例按预期工作,即调用解析方法并且测试通过:
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 中,则解析永远不会被调用:
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;
});
这里有什么问题?
我在用着Sinon 2.1.0
和本地承诺Node 6.9.5
.
问题似乎是您在超时开始之前滴答作响 - 这在第二个片段的承诺回调中异步发生。
这应该有效:
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
});
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)