diff --git a/src/index.test.ts b/src/index.test.ts index 249bbb0..356ab85 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -197,6 +197,25 @@ describe('stringify & parse', () => { }, }, + 'works for invalid dates': { + input: { + date: new Date('invalid'), + }, + output: { + date: '', + }, + outputAnnotations: { + values: { + date: ['Date'], + }, + }, + dontExpectEquality: true, + customExpectations: value => { + expect(value.date).toBeInstanceOf(Date); + expect(Number.isNaN(value.date.getTime())).toBe(true); + }, + }, + 'works for Errors': { input: { e: new Error('epic fail'), diff --git a/src/transformer.ts b/src/transformer.ts index cce7d55..536a07a 100644 --- a/src/transformer.ts +++ b/src/transformer.ts @@ -1,6 +1,5 @@ import { isBigint, - isDate, isInfinite, isMap, isNaNValue, @@ -73,9 +72,12 @@ const simpleRules = [ } ), simpleTransformation( - isDate, + (v): v is Date => v instanceof Date, 'Date', - v => v.toISOString(), + // An invalid Date (`new Date(NaN)`) has no ISO representation and would + // otherwise be dropped to `null`, losing its type. Serialize it to an + // empty string, which `new Date('')` revives back into an invalid Date. + v => (isNaN(v.valueOf()) ? '' : v.toISOString()), v => new Date(v) ),