【问题标题】:How to mock new date only when it's have no arguments?如何仅在没有参数的情况下模拟新日期?
【发布时间】:2022-01-17 18:54:45
【问题描述】:
如何用玩笑模拟new Date() 不带参数?
我看了accepted answer on stackoverflow
const mockDate = new Date(..);
const spy = jest
.spyOn(global, 'Date')
.mockImplementation(() => mockDate)
我所期望的是当 jest 运行代码时:new Date() 使用模拟。但是当它运行new Date(.....) 时会忽略模拟。
玩笑怎么办?有可能吗?
【问题讨论】:
标签:
javascript
unit-testing
jestjs
mocking
【解决方案1】:
您可以决定使用原始Date 或mockImplementation 中的模拟。
例如
describe('70349270', () => {
test('should pass', () => {
const mockDate = new Date(1639533840728);
const OriginlDate = global.Date;
jest.spyOn(global, 'Date').mockImplementation((args) => {
if (args) return new OriginlDate(args);
return mockDate;
});
// test
expect(new Date('1995-12-17T03:24:00').getTime()).toBeLessThan(1639533840728);
expect(new Date().getTime()).toBe(1639533840728);
});
});