首页 > 解决方案 > 如何在 testcafe 中模拟 Date()?

问题描述

我的测试包括根据当前日期(使用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()直接覆盖,而不是构造函数。

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

标签: dateautomated-testse2e-testingweb-testingtestcafe

解决方案


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

});

推荐阅读