Last active
February 1, 2021 13:37
-
-
Save scriptex/b0b5e39a022088728cb32ecceea2e13d to your computer and use it in GitHub Desktop.
Jest date mock (in Typescript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Mock a date which is created with the `new Date()` constructor. | |
* | |
* Usage: | |
* | |
* import { onBeforeEach, onAfterEach } from 'FOLDER/jest-date-mock'; | |
* | |
* describe('', () => { | |
* beforeEach(onBeforeEach); | |
* afterEach(onAfterEach); | |
* | |
* ... | |
* }); | |
*/ | |
const randomDate: string = '2018-12-31T23:59:59.000Z'; | |
const DateConstructor: any = Date; | |
export const onBeforeEach = (): void => { | |
(global as any).Date = jest.fn((...props) => { | |
if (props.length) { | |
return new DateConstructor(...props); | |
} | |
return new DateConstructor(randomDate); | |
}); | |
Object.assign(Date, DateConstructor); | |
}; | |
export const onAfterEach = (): void => { | |
global.Date = DateConstructor; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment