我如何在 testcafe 中模拟 Date()?

How do I mock a Date() in testcafe?

我的测试包括一个基于当前日期设置日期的步骤(使用 dayjs())。我需要始终获得相同的预定义日期。

dayjs() 调用 new Date(),所以我的方法是模拟全局 Date() 构造函数。我试过这样:


await t.eval( () => {
  const fixedDate = new Date(2010, 0, 1);
  Date = class extends Date {
    constructor() {
      super();
      return fixedDate;
    }
  };
});

像这样,testcafe 无法完成 eval(虽然在我的 Chrome 中有效)。到目前为止,我只设法直接覆盖 Date.now(),而不是构造函数。

我想知道用 eval 修改 Date 的方法是否正确,或者是否有更好的解决方案来修复当前的 Date

一种解决方案是使用 mockdate 包:

1°) npm install --save mockdate

2°) 像这样设置你的测试;

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' 

});

另一个解决方案,也使用 mockdate 包:

  1. npm i --save-dev mockdate
  2. 像这样设置测试:
fixture `My Fixture`
  .clientScripts([{module: 'mockdate'}, {content: "MockDate.set('2000-11-22')"}]);

(对于单个测试而不是固定装置,同样应该也是可能的,但还没有测试过。有关更多信息,请参阅 https://devexpress.github.io/testcafe/documentation/using-testcafe/common-concepts/inject-scripts-into-tested-pages.html。)

上面的其他解决方案不适用于我使用最新版本的 testcafe (1.7.1) 模拟页面初始化日期。在调试模式下测试 运行 期间检查浏览器控制台时,日期被模拟得很好,但它似乎在页面加载时执行我的应用程序脚本期间没有被模拟。使用 clientScripts 的解决方案为我解决了这个问题。