【问题标题】:setTimeout not triggered while using Sinon's fake timers使用诗乃的假计时器时未触发 setTimeout
【发布时间】:2017-08-20 07:14:43
【问题描述】:

我有一个类似于下面显示的测试。基本上我想测试一个特定的方法是否被延迟。

以下示例按预期工作,即调用 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 和原生承诺。

【问题讨论】:

    标签: javascript node.js promise settimeout sinon


    【解决方案1】:

    问题似乎是你在超时开始之前计时 - 这在你的第二个 sn-p 中异步发生,在一个承诺回调中。

    这应该可行:

    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
        });
      });
    });
    

    【讨论】:

    • 不得不做一些改变,但这让我走上了正确的道路!谢谢:)
    • 如果你不能改变内在的承诺,你会怎么做?我不能把clock.tick放在这里,但是promise正在等待setTimeout解决。
    • @FélixBrunet 您需要在setTimeout 调用之后的某处打勾。它也可以在new Promise 之后工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2015-08-29
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    相关资源
    最近更新 更多