Jest fake timers don't work with Zod defaults
When mocking dates in Jest, Zod does not use the mocked values when using a date in a default.
Example:
updatedTimestamp: z.string().trim().regex(ISORegex).default(new Date().toISOString()),
Testing:
const mockTimestamp = '2022-05-24T03:56:38.795Z';
jest.useFakeTimers().setSystemTime(new Date(mockTimestamp));
Or
jest.spyOn(Date.prototype, 'toISOString').mockReturnValue(mockTimestamp);
It does not use the provided date, and instead continues to use the current time.
This does not look like a zod issue. Please provide full test code to reproduce.
@ecyrbe Wanted to confirm that it is working as expected when isolated:
import { z } from 'zod';
jest.useFakeTimers().setSystemTime(new Date('2020-01-01'));
describe('test timers', () => {
it('should default to jest fake timer', () => {
const ISORegex = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
const timerTest = z.object({
updatedTimestamp: z.string().trim().regex(ISORegex).default(new Date().toISOString()),
});
const res = timerTest.parse({});
expect(res.updatedTimestamp).toBe(new Date().toISOString());
});
});
Must be a problem on my end after-all, thanks for your help