My test includes a step where the date is set based on the current date (using dayjs()
). I need to always get the same, pre-defined date.
dayjs() calls new Date()
, so my approach was to mock the global Date()
constructor. I've tried it like this:
await t.eval( () => {
const fixedDate = new Date(2010, 0, 1);
Date = class extends Date {
constructor() {
super();
return fixedDate;
}
};
});
Like this, testcafe can't finish to eval
(works in my Chrome though). So far, I only managed to overwrite Date.now()
directly, but not the constructor.
I wonder if the approach to modifying Date
with eval
is the right approach or if there's any better solution how to fixate the current Date
.
Use the RequestMock constructor to create a mocker. Call the onRequestTo and respond methods in a chain to specify mock responses for every handled request. To use the mocker during tests, attach it to a test or fixture. No WebDriver required.
TestCafe is easy to use since it doesn't require an external driver to run end-to-end tests in the browser. It supports a wide variety of browsers and platforms, including Google Chrome, Internet Explorer (11+), Mozilla Firefox, Safari, Microsoft Edge, Opera, and Google Chrome mobile.
eval(() => location. reload(true));
One solution is to use the mockdate
package:
1°) npm install --save mockdate
2°) set up your test like this;
import { ClientFunction } from 'testcafe';
import { readFileSync } from 'fs';
import { join } from 'path';
test('Test', async t => {
const mockdateJS = readFileSync(join(process.cwd(), 'node_modules','mockdate','src','mockdate.js')).toString();
const loadJsLib = ClientFunction((js) => {
window.MockDate = new Function(js);
window.MockDate();
});
const setDate = ClientFunction((date) => window.MockDate.set(date));
await loadJsLib(mockdateJS); // dynamically load the mockdate lib in browser
await setDate('2000-11-22'); // mock date in browser
// now any code in the browser that does new Date() will get '2000-11-22'
});
Another solution, also using the mockdate
package:
npm i --save-dev mockdate
fixture `My Fixture`
.clientScripts([{module: 'mockdate'}, {content: "MockDate.set('2000-11-22')"}]);
(The same should also be possible for single tests instead of fixtures, but have not tested that yet. See https://devexpress.github.io/testcafe/documentation/using-testcafe/common-concepts/inject-scripts-into-tested-pages.html for more info.)
The other solution above did not work for me with the latest version of testcafe (1.7.1) for mocking the date on page initialisation. When checking the browser console during the test run in debug mode, the date was mocked alright, but it seems like it was not mocked during execution of my app's scripts on page load. The solution using clientScripts
fixed that for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With