diff --git a/cli/js/tests/console_test.ts b/cli/js/tests/console_test.ts index bceee94190..4a227aafe1 100644 --- a/cli/js/tests/console_test.ts +++ b/cli/js/tests/console_test.ts @@ -1067,6 +1067,15 @@ unitTest(function consoleLogShouldNotThrowError(): void { }); }); +// console.log(Invalid Date) test +unitTest(function consoleLogShoultNotThrowErrorWhenInvalidDateIsPassed(): void { + mockConsole((console, out) => { + const invalidDate = new Date("test"); + console.log(invalidDate); + assertEquals(out.toString(), "Invalid Date\n"); + }); +}); + // console.dir test unitTest(function consoleDir(): void { mockConsole((console, out): void => { diff --git a/cli/js/web/console.ts b/cli/js/web/console.ts index 5544ded3c0..4709697d2e 100644 --- a/cli/js/web/console.ts +++ b/cli/js/web/console.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { isTypedArray, TypedArray } from "./util.ts"; +import { isInvalidDate, isTypedArray, TypedArray } from "./util.ts"; import { cliTable } from "./console_table.ts"; import { exposeForTest } from "../internals.ts"; import { PromiseState } from "./promise.ts"; @@ -409,8 +409,7 @@ function createWeakMapString(): string { } function createDateString(value: Date): string { - // without quotes, ISO format - return value.toISOString(); + return isInvalidDate(value) ? "Invalid Date" : value.toISOString(); // without quotes, ISO format } function createRegExpString(value: RegExp): string { diff --git a/cli/js/web/util.ts b/cli/js/web/util.ts index 824d00d4b0..0ab367554a 100644 --- a/cli/js/web/util.ts +++ b/cli/js/web/util.ts @@ -18,6 +18,11 @@ export function isTypedArray(x: unknown): x is TypedArray { return ArrayBuffer.isView(x) && !(x instanceof DataView); } +// @internal +export function isInvalidDate(x: Date): boolean { + return isNaN(x.getTime()); +} + // @internal export function requiredArguments( name: string,