7

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.

Alex Skorkin
  • 4,264
  • 3
  • 25
  • 47
Kim
  • 73
  • 5

2 Answers2

6

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' 

});
hdorgeval
  • 3,000
  • 8
  • 17
5

Another solution, also using the mockdate package:

  1. npm i --save-dev mockdate
  2. set up the tests like this:
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.

jule
  • 51
  • 1
  • 2
  • ..not sure if one sentence makes your answer readable... please revise properly. – ZF007 Dec 31 '19 at 13:02
  • 1
    see the executable example [here](https://github.com/DevExpress/testcafe-examples/tree/master/examples/mock-date) – mlosev Oct 12 '20 at 08:25