This question is similar to How do I set a timezone in my Jest config? but all the answers there pertain to *nix.
How do you set the timezone for jest tests when running Windows 10?
This question is similar to How do I set a timezone in my Jest config? but all the answers there pertain to *nix.
How do you set the timezone for jest tests when running Windows 10?
OK! Thanks for the comments and answers. It got me pointed in a good direction.
set-tz
is cool but the cleanup()
function wasn't firing when the tests completed.
That, combined with tzutil
changing the Windows system time, forced me to think about minimizing the impact of the timezone change and having a way to force it back instead of relying on an exit-listener.
So, here's where it landed.
// setTimezone file.
const { execSync } = require('child_process');
const os = require('os');
export const setTimezone = (TZ) => {
if (os.platform() === 'win32') {
process.env.STORED_TZ = execSync('tzutil /g').toString();
execSync(`tzutil /s "${TZ}"`);
console.warn(`Windows timezone changed from "${process.env.STORED_TZ}" to "${TZ}"\nRun \`tzutil /s "${process.env.STORED_TZ}"\` to set it back manually.`);
} else {
process.env.TZ = TZ;
}
};
export const restoreTimezone = () => {
if (os.platform() === 'win32') {
execSync(`tzutil /s "${process.env.STORED_TZ}"`);
console.warn(`Windows timezone restored to "${process.env.STORED_TZ}"`);
} else {
process.env.TZ = process.env.STORED_TZ;
}
};
Here's an example of where we use it.
// test file
import * as dtt from './dateTimeTools';
import typeOf from './funcs/typeOf';
import { restoreTimezone, setTimezone } from './setTimezone';
const inputs = {
dateOnly: '2020-01-01',
dateTimeWithoutTimezone: '2020-01-01T00:00:00.000000',
midnightNewYorkTimezone: '2020-01-01T00:00:00.000000-05:00',
};
describe('dateTimeTools > isoToDate', () => {
setTimezone('Pacific Standard Time'); //
assert({
given: 'any valid ISO string.',
should: 'return a date object.',
actual: typeOf(dtt.isoToDate(inputs.dateOnly)),
expected: 'date',
});
assert({
given: 'a date-only ISO string.',
should: 'return the given date at midnight in the local timezone.',
actual: dtt.isoToDate(inputs.dateOnly).toString(),
expected: 'Wed Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)',
});
restoreTimezone(); //
});
I believe you can solve it by using set-tz package
const setTZ = require('set-tz')
setTZ('America/New_York')