From dbbd9e5e0bb1e766910809da77e5a6126897202a Mon Sep 17 00:00:00 2001 From: ttoohey Date: Wed, 7 Apr 2021 17:57:01 +1000 Subject: [PATCH] fix: handle invalid Date objects (#605) (#606) calling toISOString() on an invalid Date object will throw a Range Error --- src/formatter/formatPropValue.js | 3 +++ src/formatter/formatPropValue.spec.js | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/src/formatter/formatPropValue.js b/src/formatter/formatPropValue.js index 19b2b2884..1044e3b37 100644 --- a/src/formatter/formatPropValue.js +++ b/src/formatter/formatPropValue.js @@ -54,6 +54,9 @@ const formatPropValue = ( } if (propValue instanceof Date) { + if (isNaN(propValue.valueOf())) { + return `{new Date(NaN)}`; + } return `{new Date("${propValue.toISOString()}")}`; } diff --git a/src/formatter/formatPropValue.spec.js b/src/formatter/formatPropValue.spec.js index 62dfb8b37..8d0a0eeb4 100644 --- a/src/formatter/formatPropValue.spec.js +++ b/src/formatter/formatPropValue.spec.js @@ -93,6 +93,12 @@ describe('formatPropValue', () => { ).toBe('{new Date("2017-01-01T11:00:00.000Z")}'); }); + it('should format an invalid date prop value', () => { + expect(formatPropValue(new Date(NaN), false, 0, {})).toBe( + '{new Date(NaN)}' + ); + }); + it('should format an object prop value', () => { expect(formatPropValue({ foo: 42 }, false, 0, {})).toBe( '{*Mocked formatComplexDataStructure result*}'