Skip to content

Instantly share code, notes, and snippets.

@dklassen
Last active November 21, 2018 19:11
Show Gist options
  • Save dklassen/fb9a54eadcc7b248bd1f114b5693abd2 to your computer and use it in GitHub Desktop.
Save dklassen/fb9a54eadcc7b248bd1f114b5693abd2 to your computer and use it in GitHub Desktop.
Mocking global date
// source: https://github.com/facebook/jest/issues/2234
let timeNow;
const realDate = Date;
describe("Stubbed Date", () => {
beforeAll(() => {
timeNow = Date.now();
const _GLOBAL: any = global;
_GLOBAL.Date = class {
public static now() {
return timeNow;
}
constructor() {
return timeNow;
}
public valueOf() {
return timeNow;
}
};
});
afterAll(() => {
global.Date = realDate;
});
it("provides constant timestamps", () => {
const ts1 = Date.now();
const ts2 = +new Date();
expect(ts1).toEqual(ts2);
expect(ts2).toEqual(timeNow);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment