jest typescript - 模拟日期构造函数

2024-01-01

我试图嘲笑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'.

我认为原因是笑话认为我试图嘲笑Date()代替new Date()。的确,Date()返回一个字符串。我该如何解决这个问题?


好吧,我尝试了这个解决方案,它有效..

class MockDate extends Date {
    constructor() {
        super("2020-05-14T11:01:58.135Z"); // add whatever date you'll expect to get
    }
}

在该测试的 beforeEach 中,我添加了:

// @ts-ignore
global.Date = MockDate;

这样,每当我调用一个内部有 new Date() 的函数时,它都会返回我在上面 MockDate 类的构造函数中添加的日期!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jest typescript - 模拟日期构造函数 的相关文章