我正在尝试模拟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()
返回一个字符串。我该如何解决这个问题?
答案 0 :(得分:8)
好吧,我尝试了这种解决方案,并且奏效了。
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;
这样,每当我调用的函数中包含新的Date()时,它将返回我在上面的MockDate类的构造函数中添加的日期!
答案 1 :(得分:4)
一种解决方法是使用mockdate库,该库可以在“ now”为现时进行更改。
const MockDate = require('mockdate');
test('Mock Date to change when "now" is', () => {
console.log('Normal: ', new Date().getTime());
MockDate.set(new Date(1466424490000));
console.log('Mocked: ', new Date().getTime());
MockDate.reset();
console.log('Restored: ', new Date().getTime());
});
测试结果如下:
$ npm run test
> jest
PASS src/test.ts
✓ Mock Date to change when "now" is (8ms)
console.log src/test.ts:4
Normal: 1585505136315
console.log src/test.ts:8
Mocked: 1466424490000
console.log src/test.ts:12
Restored: 1585505136322
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.804s
答案 2 :(得分:1)
只需告诉编译器它想听什么:说一下将其强制转换为未知的字符串,然后将其强制转换为字符串:
const now = new Date() as unknown as string
答案 3 :(得分:1)
Daryn 对 Arron 的回答的推理评论在没有额外包的情况下效果很好。
const mockDate = new Date();
jest.spyOn(global, "Date").mockImplementation(() => (mockDate as unknown) as string);
const myDate = new Date();