Sinonjs-将时钟提前到59分钟,并实际等待1分钟

人气:890 发布:2022-10-16 标签: javascript sinon

问题描述

我有一个用于自动注销功能的Web组件,它显示了第59分钟的消息模式窗口,并在没有活动的情况下再停留一分钟。如果用户没有点击窗口上的任何位置,则注销该用户。因此,一小时内没有任何活动将自动注销用户。该功能工作正常。

现在,为了测试此功能,我尝试使用sinonjs。我使用了FakeTimers,但无法达到效果。我正在尝试测试显示消息的模式窗口。

代码如下:

const { When } = require('cucumber'); // eslint-disable-line import/no-extraneous-dependencies
const fs = require('fs');
const path = require('path');

let clock;    

async function setupSinon() {
  const sinonPath = require.resolve('sinon');

  const content = await new Promise((resolve, reject) => {
    fs.readFile(
      path.join(sinonPath, '../../pkg/sinon.js'),
      'utf-8',
      async (error, cont) => {
        if (error) return reject(error);
        resolve(cont);
      },
    );
  });
  // creating <script> element for sinonjs to execute on the page
  await browser.execute((content) => {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.text = content;
    document.head.appendChild(script);
  }, content);
}

async function iWaitForNMinutes() {
  await setupSinon();
  await browser.execute(() => {
    before(() => {
      clock = sinon.useFakeTimers();
    });
    clock = sinon.useFakeTimers({
      now: Date.now(),
      shouldAdvanceTime: true,
      toFake: ['setTimeout'],
    });

    clock.tick('59:00'); // advancing the clock to 59 minutes so that auto-logout modal window popup, but this doesn't work

    after(() => {
      clock.restore();
    });

    setTimeout(() => {}, 60000);

  });
} 

When(/^I wait for minutes$/, iWaitForNMinutes);

module.exports = {      
  iWaitForNMinutes,
};

sinon 5.0.10

如何使用sinonjsFakeTimer将时间提前到n分钟,然后实际等待n分钟?

推荐答案

SNON的假计时器非常容易使用,也是我最喜欢的SINON功能。

用法如下

在您的代码中

// in your code
eatCake() {
  setTimeout(function() {
    // eat cake after 10s
  }, 10000); // 10000 === 10s
}

在您的测试中

clock = sinon.useFakeTimers();
clock.tick(9000);
// check if cake is eaten - answer will be false
clock.tick(1000); // 9000 + 1000 === 10s
// check if cake is eaten - answer will be true

所以SINON基本上(以编程方式)快进计时器,这样我们的测试就可以检查所需的结果,而无需实际等待时间,因为所有测试框架通常都有2秒的等待超时,在此之后测试用例将失败。

在您的情况下,要等待59分钟,您可以写

clock.tick(1000 * 60 * 59); // 59 minutes

// check if the modal has opened up

clock.tick(1000 * 60 * 1); // 1 minute

// check if the user is logged out

并且不要忘记在结束时恢复时钟,就像您已经做的那样。

clock.restore();

811