zod icon indicating copy to clipboard operation
zod copied to clipboard

Jest fake timers don't work with Zod defaults

Open MylesSmart opened this issue 3 years ago • 1 comments

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.

MylesSmart avatar Jun 14 '22 16:06 MylesSmart

This does not look like a zod issue. Please provide full test code to reproduce.

ecyrbe avatar Jun 19 '22 17:06 ecyrbe

@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

MylesSmart avatar Aug 22 '22 17:08 MylesSmart