date - 如何在 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
.
解决方案
一种解决方案是使用该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'
});
推荐阅读
- python - 在文本文件的列中查找局部最大值
- yii2 - 如何通过 ActiveForm (Yii2) 中的 hiddenInput 发送 url(id)
- intellij-idea - IntelliJ 未找到 JavaFX
- python - 如何在 python 中使用单引号格式化 SQL where 子句参数?
- powershell - 将 Get-NetTCPConnection 的输出写入数组 - 无输出
- mysql - 如何更改或交换与一列相关的值?
- sql - 嵌套事务和@@trancount 计数(70-761 练习题的问题)
- plot - 不同的 x 轴范围系统 GLE 中的图表
- .net-core - 在 HeroCard 中发送 CardActions 作为欢迎信息并直接进入相应的对话框
- .net-core - 如何在同一个项目中创建具有 Angular7 + WebAPI + AzureAD 的 .NET Core 应用程序