我的测试包括根据当前日期设置日期的步骤(使用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
。
一种解决方案是使用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'
});