Search code examples
dateautomated-testse2e-testingweb-testingtestcafe

How do I mock a Date() in testcafe?


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.


Solution

  • 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' 
    
    });