Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Created July 25, 2022 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barbietunnie/228f17a4f3f6cd85b6f62d0d651a7f11 to your computer and use it in GitHub Desktop.
Save barbietunnie/228f17a4f3f6cd85b6f62d0d651a7f11 to your computer and use it in GitHub Desktop.
How to mock a date in Jest

How to set a mock date in Jest

To mock a date in Jest, we can use the useFakeTimers and setSysttemTime methods.

jest
  .useFakeTimers('modern')
  .setSystemTime(new Date('2020-08-09'));

For clean up, you can reset it with

jest.useRealTimers()

One of the places you can cleanup is in afterEach(), likewise you can apply the mock dates for all tests in beforeEach(). e.g.

beforeEach(() => {
    jest.useFakeTimers('modern')
        .setSystemTime(new Date('2020-08-09'))
})

afterEach(() => {
    jest.runOnlyPendingTimers()
    jest.useRealTimers()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment