diff --git a/src/duration.js b/src/duration.js index 49033a47..56cf194b 100644 --- a/src/duration.js +++ b/src/duration.js @@ -462,6 +462,8 @@ export default class Duration { * ``` */ toHuman(opts = {}) { + if (!this.isValid) return INVALID; + const l = orderedUnits .map((unit) => { const val = this.values[unit]; @@ -576,9 +578,11 @@ export default class Duration { * @return {number} */ toMillis() { + if (!this.isValid) return NaN; + let sum = this.values.milliseconds ?? 0; for (let unit of reverseUnits.slice(1)) { - if (this.values?.[unit]) { + if (this.values[unit]) { sum += this.values[unit] * this.matrix[unit]["milliseconds"]; } } diff --git a/test/duration/invalid.test.js b/test/duration/invalid.test.js index 98f5e920..ffde586a 100644 --- a/test/duration/invalid.test.js +++ b/test/duration/invalid.test.js @@ -31,3 +31,23 @@ test("Diffing invalid DateTimes creates invalid Durations", () => { test("Duration.invalid produces invalid Intervals", () => { expect(Duration.invalid("because").isValid).toBe(false); }); + +test("Duration.toMillis produces NaN on invalid Durations", () => { + expect(Duration.invalid("because").toMillis()).toBe(NaN); +}); + +test("Duration.as produces NaN on invalid Durations", () => { + expect(Duration.invalid("because").as("seconds")).toBe(NaN); +}); + +test("Duration.toHuman produces null on invalid Durations", () => { + expect(Duration.invalid("because").toHuman()).toBe("Invalid Duration"); +}); + +test("Duration.toISO produces null on invalid Durations", () => { + expect(Duration.invalid("because").toISO()).toBeNull(); +}); + +test("Duration.toFormat produces Invalid Duration on invalid Durations", () => { + expect(Duration.invalid("because").toFormat("s")).toBe("Invalid Duration"); +});