How to test components using Date objects produce different snapshots in different timezones with Jest?

Sometimes, we want to test components using Date objects produce different snapshots in different timezones with Jest.

In this article, we’ll look at how to test components using Date objects produce different snapshots in different timezones with Jest.

How to test components using Date objects produce different snapshots in different timezones with Jest?

To test components using Date objects produce different snapshots in different timezones with Jest, we can use the timezone-mock package.

To install it, we run npm i timezone-mock.

Then we write

import timezoneMock from 'timezone-mock';

describe('when in Pacific timezone', () => {
  beforeAll(() => {
    timezoneMock.register('US/Pacific');
  });

  afterAll(() => {
    timezoneMock.unregister();
  });

  // ...
})

to call timezoneMock.register with the time zone we want to run our tests in.

And then we call timezoneMock.unregister to restore the test environment to its original time zone.

Conclusion

To test components using Date objects produce different snapshots in different timezones with Jest, we can use the timezone-mock package.