Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,25 @@ describe('stringify & parse', () => {
},
},

'works for invalid dates': {
input: {
date: new Date('invalid'),
},
output: {
date: '',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's use Invalid Date as the sentinel value instead of ''.

},
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'),
Expand Down
8 changes: 5 additions & 3 deletions src/transformer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
isBigint,
isDate,
isInfinite,
isMap,
isNaNValue,
Expand Down Expand Up @@ -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)
),

Expand Down