如何在testcafe中模拟Date()?

问题描述 投票:3回答:1

我的测试包括根据当前日期设置日期的步骤(使用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

date automated-tests e2e-testing web-testing testcafe
1个回答
3
投票

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

});
© www.soinside.com 2019 - 2024. All rights reserved.