javascript - 如何同时模拟 Date.now 多次
问题描述
我正在尝试实现我自己的模拟日期函数,我希望它能够同时工作。
我认为最佳用法是:
mockDate(myFirstDate, async () => {
// Here and only here Date.now() === myFirstDate
})
mockDate(mySecondDate, async () => {
// Here and only here Date.now() === mySecondDate
})
// Outside Date.now is working as expected
这是我要实现的最小失败代码示例:
async function mockDate(timestamp, callback) {
const original_now = Date.now
Date.now = function() {
if (/* How can I check Date.now have been called inside callback */ true) return timestamp
else return original_now()
}
await callback()
Date.now = original_now
}
const wait = ms => new Promise(res => setTimeout(res, ms))
mockDate(1600000000000, async () => {
await wait(100)
const result = Date.now()
if (result !== 1600000000000) throw new Error('Fail: 1600000000000')
}).catch(console.error)
mockDate(1650000000000, async () => {
const result = Date.now()
if (result !== 1650000000000) throw new Error('Fail: 1650000000000')
await wait(200)
}).catch(console.error)
我的想法是检查内部if
是否可以检索callback
内部this.caller
。不幸的是,访问this.caller
给了我一个错误。
我也知道测试框架通常有串行模式,但我试图避免它。
解决方案
禁用严格模式或使用串行模式。
推荐阅读
- c++ - break 语句没有退出循环
- scala - 在启动主逻辑之前处理 Actor 需求
- mqtt - Mosquitto bridge CPU消耗随时间增加
- asp.net - Asp.Net:在 Application_End 上发送 SignalR 消息
- ios - 无法传输工件 com.mobidevelop.robovm
- swift - 分隔线出现早于单元格标题并且图像超出 UIImageView
- node.js - message.reply 中的 Discord.js 用户输入
- elasticsearch - Elasticsearch 查询聚合过滤器需要的范围建议
- md5 - 如果输入字符串仅包含字母数字,md5 消化的冲突概率是多少
- selenium - 需要帮助理解流畅的等待Java代码