问题
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;
},
};
回答1:
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
回答2:
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;
});
来源:https://stackoverflow.com/questions/36232948/how-to-use-fake-timers-with-nightwatch-js-and-sinon-js