-
-
Save bbshih/1cac2e30e5884102a66a07fbe464b50c to your computer and use it in GitHub Desktop.
// 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; | |
}); |
This gist was of great help to me. I found another way of mocking the timezone with a fixed value.
jest.mock('moment', () => () => (jest.requireActual('moment-timezone')).tz('2021-01-01T00:00:00.000Z', 'GMT'));
Hi i tried const moment = require('moment-timezone')
moment.tz.setDefault('Antarctica/Vostok') // Whatever timezone you want
jest.setMock('moment', moment)
it is giving me original user's time zone not the mocked one
any one please help me
export class DateTzPipe implements PipeTransform {
transform(x: any) {
const y = moment.tz(x, 'America/Panama').format();
const errorDate = new Date(y);
const timeZoneString = moment.tz.guess() === 'Pacific/Port_Moresby' ? 'CHST' : moment.tz(moment.tz.guess()).format('z');
return (moment.tz(errorDate,moment.tz.guess()).format('MM/DD/YYYY - hh:mm:ss A') + " " + timeZoneString);
}
test:
const moment = require('moment-timezone')
moment.tz.setDefault('America/New_york') // Whatever timezone you want
jest.setMock('moment', moment)
describe('transform', () => {
let datePipe:DateTzPipe;
beforeEach(() => {
datePipe=new DateTzPipe();
});
it('Should transform measures without a strat expression', () => {
expect(datePipe.transform('2021-09-07T19:23:44.309871')).toBe('09/07/2021 - 08:23:44 PM EDT');
});
If you're still struggling with timezones, try this https://www.npmjs.com/package/timezone-mock it saved my day.
@pimlie thank you! Your solution works
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.
Had the same error as @a-reda, the following code worked for me: