【发布时间】:2020-07-09 17:28:45
【问题描述】:
我正在尝试模拟 new Date() 以返回特定日期。以下代码:
const now = new Date()
jest.spyOn(global, 'Date').mockImplementation(() => now)
给出编译错误:Argument of type '() => Date' is not assignable to parameter of type '() => string'. Type 'Date' is not assignable to type 'string'。
我认为原因是 jest 认为我试图模拟 Date() 而不是 new Date()。实际上,Date() 返回一个字符串。我该如何解决这个问题?
【问题讨论】:
-
找到解决方案了吗?
-
不。我使用了一种解决方法:我只在我的代码中使用
new Date(Date.now())而从不使用new Date()。这样我就可以模拟Date.now()。
标签: typescript unit-testing mocking jestjs spy