Skip to content

Instantly share code, notes, and snippets.

@bengry
Last active May 24, 2021 11:11
Show Gist options
  • Save bengry/2175edcc13ba910f1edc2f331fcec46b to your computer and use it in GitHub Desktop.
Save bengry/2175edcc13ba910f1edc2f331fcec46b to your computer and use it in GitHub Desktop.
import timezonedDate from "timezoned-date";
export interface MockDateSetup {
reset(): void;
set(options: { offset?: number | keyof typeof offsetsByName; isoDate?: string }): void;
}
const originalDate = Date;
export function setupMockDate(): MockDateSetup {
function reset() {
Date = originalDate;
}
function set({ isoDate, offset }: { offset?: number; isoDate?: string }) {
const getMockDate = (): typeof import("mockdate") => {
let MockDate: typeof import("mockdate") | undefined;
jest.isolateModules(() => {
MockDate = require("mockdate");
});
return MockDate!;
};
if (offset !== undefined) {
Date = timezonedDate.makeConstructor(offset);
}
if (isoDate !== undefined) {
getMockDate().set(isoDate);
}
}
return { reset, set };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment