-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Set consistent timezone for tests #209
Conversation
I don't think I fully understand the motivation behind this change. I would imagine that if we run into a situation where a test passes/fails due to timezone differences, that that would indicate a potential issue in either (a) the source code or (b) the testing code. So this change might actually hide those sorts of bugs by making it seem like everything is running in the same timezone. Are there examples of tests we actually want to have assumptions on the timezone? |
@lorenyu That's a good point. I was imagining a page that shows a date/time in the current user's timezone, which could vary, so the source code wouldn't define a specific timezone. Happy to revert this if you think the mocking implementation in tests should be left up to project teams. |
Thanks for sharing that example. For that use case, I would put that in the test itself. e.g. something like:
that's just pseudocode but basically if the specific functionality / test cares about timezone, then just set it in that test. all other tests should be agnostic to timezone, and if they fail for some reason that probably indicates a deeper issue we shouldn't paper over. |
I ran into an issue again where a globally defined timezone would have been helpful. The root of the issue, I think, is that
From one of the Node.js contributors:
Here's the test I was trying to write: it('reuses the token until it expires', async () => {
// Set system to non-UTC just to ensure our implementation is taking timezones into account:
process.env.TZ = 'America/Los_Angeles'
jest.useFakeTimers({
// Mock current time, in PT time:
now: new Date('2043-10-30 19:00:00.000000'),
})
const spy = jest.spyOn(axios, 'post').mockResolvedValue({
data: {
data: {
token: 'mock-token',
// One hour in the future, but in UTC time
expiration: '2043-10-31 02:00:00.000000',
},
},
})
const persistence = new PersistenceAPI({ baseUrl: MOCK_BASE_URL })
// First token request results in an API call:
await persistence.getToken()
expect(spy).toHaveBeenCalledTimes(1)
// Still only 1 API call after the second request:
await persistence.getToken()
expect(spy).toHaveBeenCalledTimes(1)
// New API call after the token gets within 5 minutes of expiring:
jest.setSystemTime(new Date('2043-10-30 19:55:00.000000'))
await persistence.getToken()
expect(spy).toHaveBeenCalledTimes(2)
}) |
Interesting. How about this https://www.npmjs.com/package/timezone-mock Looks like it mocks the time zone by replacing Date constructor |
Changes