首页 > 解决方案 > 如何同时模拟 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给了我一个错误。

我也知道测试框架通常有串行模式,但我试图避免它。

标签: javascriptnode.jsunit-testingmocking

解决方案


禁用严格模式或使用串行模式。


推荐阅读