如何在 testcafe 中模拟 Date()?

Kim*_*Kim 6 automated-tests date web-testing e2e-testing testcafe

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

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


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

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

我想知道修改Datewitheval的方法是否是正确的方法,或者是否有更好的解决方案来固定当前的Date.

hdo*_*val 6

一种解决方案是使用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' 

});
Run Code Online (Sandbox Code Playgroud)


jul*_*ule 5

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

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

(对于单个测试而不是固定装置也应该可以进行相同的操作,但尚未进行测试。请参阅https://devexpress.github.io/testcafe/documentation/using-testcafe/common-concepts/inject-scripts-into-欲了解更多信息,请访问tested-pages.html 。)

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