使用 Sinon 的假计时器时未触发 setTimeout [英] setTimeout not triggered while using Sinon's fake timers

查看:53
本文介绍了使用 Sinon 的假计时器时未触发 setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于下图所示的测试.基本上我想测试一个特定的方法是否被延迟了.

I have a test similar to what is shown below. Basically I want to test if a specific method is getting delayed.

以下示例按预期工作,即调用了 resolve 方法并且测试通过:

The following example works as expected, i.e. the resolve method gets called and the test passes:

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 中,则解析永远不会被调用:

However, if I wrap the setTimeout in another Promise, the resolve never gets called:

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 和本机承诺.

I'm using Sinon 2.1.0 and native promises on Node 6.9.5.

推荐答案

问题似乎是您在超时开始之前正在计时 - 这在第二个代码段中的 promise 回调中异步发生.

The problem appears to be that you are ticking the clock before the timeout is started - which happens asynchronously, in a promise callback, in your second snippet.

>

这应该有效:

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

这篇关于使用 Sinon 的假计时器时未触发 setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆