Skip to content

Instantly share code, notes, and snippets.

@scriptex
Last active February 1, 2021 13:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scriptex/b0b5e39a022088728cb32ecceea2e13d to your computer and use it in GitHub Desktop.
Save scriptex/b0b5e39a022088728cb32ecceea2e13d to your computer and use it in GitHub Desktop.
Jest date mock (in Typescript)
/**
* 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