Skip to content

Instantly share code, notes, and snippets.

@christophermark
Created December 7, 2020 19:38
Show Gist options
  • Save christophermark/d2631e0ac7bccf38bf2c257e106732fd to your computer and use it in GitHub Desktop.
Save christophermark/d2631e0ac7bccf38bf2c257e106732fd to your computer and use it in GitHub Desktop.
Forcing system time for jest tests
/**
* Set the system time for our tests.
* This ensures that our tests can't fail based on the local time of the CI machine.
* This guards against app code where the behavior changes based on the device time.
* For example, a test might fail if we attempt to set the search time "before now".
*/
beforeAll(() => {
// @TODO: 'modern' is default once we upgrade to Jest 27 https://jestjs.io/blog/2020/05/05/jest-26#new-fake-timers
jest.useFakeTimers("modern");
const JS_DATE_11_AM = new Date(new Date().setHours(11, 0, 0, 0));
// This is a typical time during the workday, during our mock building working hours.
const DEFAULT_TEST_TIME = JS_DATE_11_AM;
jest.setSystemTime(DEFAULT_TEST_TIME);
});
afterAll(() => {
// Undo the forced time we applied earlier, reset to system default.
jest.setSystemTime(jest.getRealSystemTime());
jest.useRealTimers();
});
// Why didn't this work?
// The new "modern" timer mocks in jest were breaking some internal async part of Redux Saga - it would never resolve.
// Switching to the default timer mock (`.useFakeTimers()`) fixes the issue, but that doesn't
// support setting the system time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment