How to use Fake timers with nightwatch.js and sinon.js?

旧巷老猫 提交于 2019-12-05 18:40:35

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")

Or you can use lolex (more compact) like this

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

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

The actual command is the file fakeDate.js

I found the solution. As Vincent J and his gist mentioned, I needed to inject lolex into the browser.

I used just lolex. I inject it to the browser like below.

if (__E2E__) {
  window.lolex = require('lolex');
}

And I execute it for setting the time.

browser
  .execute(function () {
    const clock = window.lolex.createClock(new Date(2015, 7, 20, 19, 45));
    window.Date = clock.Date;
  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!