Skip to content

Instantly share code, notes, and snippets.

@bbshih
Forked from lededje/gist:44aeddf1dc2a5e6064e3b29dc35a7a2d
Last active February 22, 2023 18:27
Show Gist options
  • Save bbshih/1cac2e30e5884102a66a07fbe464b50c to your computer and use it in GitHub Desktop.
Save bbshih/1cac2e30e5884102a66a07fbe464b50c to your computer and use it in GitHub Desktop.
Jest Mocking Moment to same time zone for tests
// To mock globally in all your tests, add to setupTestFrameworkScriptFile in config:
// https://facebook.github.io/jest/docs/en/configuration.html#setuptestframeworkscriptfile-string
jest.mock('moment', () => {
const moment = require.requireActual('moment-timezone');
moment.tz.setDefault('America/Los_Angeles'); // Whatever timezone you want
return moment;
});
@AndrejJurkin
Copy link

If you're still struggling with timezones, try this https://www.npmjs.com/package/timezone-mock it saved my day.

@Pacheco95
Copy link

@pimlie thank you! Your solution works

@stevenirby
Copy link

None of these worked for me. I realized this is simply the wrong approach (depending on what you need).

I ended up doing this instead:

test('test thing', () => {
  jest.useFakeTimers();
  jest.setSystemTime(new Date('2023-01-01'));
  expect(fn).toEqual(thing);
  jest.setSystemTime(new Date());
});

IMHO, it is best to avoid monkey-patching moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment