如何在nightwatch.js和sinon.js中使用假计时器? [英] How to use Fake timers with nightwatch.js and sinon.js?

查看:146
本文介绍了如何在nightwatch.js和sinon.js中使用假计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nightwatch.js进行JavaScript e2e测试,并且我想使用sinon.js的假计时器模拟时钟

I'm doing JavaScript e2e test with nightwatch.js, and I want to mock the clock with sinon.js's fake timer http://sinonjs.org/docs/#clock

但是测试在完成之前就停止了,我得到了如下所示的日志,并且不再进行了.

But test stops before finish it, I got the log like below, and doesn't progress anymore.

[some test] Test Suite
===============================
 ✔ Element <body> was visible after 5000 milliseconds. 

我的测试代码如下.我该如何解决这个问题?谢谢.

My test code is like below. How can I solve the problem? Thank you.

module.exports = {
  before: function(browser) {
    clock = sinon.useFakeTimers(new Date(2015, 7, 20).getTime());
  },

  after: function(browser) {
    clock.restore();
    browser.end();
  },

  'some test': function(browser) {
    const browserName = this.client.options.desiredCapabilities.browserName;

    browser
      .url('some/path/')
      .waitForElementVisible('body', 5000)
      .pause(5000); // I need to use pause here

    clock.tick(5001);

    browser
      .expect.element('.someElement').to.be.enabled;
  },
};

推荐答案

问题是,当您使用sinon伪时钟时,时钟被冻结,并且所有异步操作均不起作用(它们等待您提高时钟频率) . 如果您只想使用伪造的日期,则可以这样写:

The problem is that when you are using sinon fake clock, the clock is freezed and everything async doesn't work (they wait for you to advance the clock). If you just want to use a fake Date, you can write it like this:

clock = sinon.useFakeTimers(new Date(2015, 7, 20).getTime(), "Date")

或者您可以像这样使用lolex(更紧凑)

Or you can use lolex (more compact) like this

clock = lolex.install(new Date(2015,7,20), ["Date"]);

但是您的代码有问题. 当您在测试中将时钟替换为假时钟时,您只是在测试代码中伪造了时钟,而不是在浏览器中伪造了时钟. 要假冒浏览器时钟,必须加载要测试的页面,并且必须向其中注入lolex(或sinon)代码,然后触发伪造. 这花了我几个小时才终于弄清楚,并且我使用lolex创建了nigthwatch命令来简化此操作. 您可以在这里找到代码:

BUT there is a problem with your code. When you are replacing the clock with the fake clock in your test, you are just faking the clock in the test code, NOT in the browser. For the browser clock to be faked, the page you want to test must be loaded, and you have to inject lolex (or sinon) code into it, then trigger the faking. This took me a few hours to finally figure it out and i have created a nigthwatch command using lolex to make this much easier. You can find the code here :

https://gist.github.com/vjau/9a8db88d5f1f82d4f9c02e82b29b466f

实际命令是文件fakeDate.js

The actual command is the file fakeDate.js

这篇关于如何在nightwatch.js和sinon.js中使用假计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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