问题
I'm trying to mock new Date()
to return a specific date. The following code:
const now = new Date()
jest.spyOn(global, 'Date').mockImplementation(() => now)
gives a compilation error: Argument of type '() => Date' is not assignable to parameter of type '() => string'. Type 'Date' is not assignable to type 'string'
.
I think the reason is that jest thinks I'm trying to mock Date()
instead of new Date()
. Indeed, Date()
returns a string. How can I solve this issue?
回答1:
A workaround is to use the mockdate library, which can be used to change when "now" is.
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());
});
And the test result is like:
$ 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
See the reference project on GitHub.
来源:https://stackoverflow.com/questions/60912023/jest-typescript-mock-date-constructor