From 034505e0372d43ee26ba28d13ff9443e2bf8f2c2 Mon Sep 17 00:00:00 2001 From: Aviv Keller Date: Sun, 17 Nov 2024 05:25:12 -0500 Subject: [PATCH] test_runner: error on mocking an already mocked date Fixes #55849 PR-URL: https://github.com/nodejs/node/pull/55858 Reviewed-By: Jacob Smith Reviewed-By: Colin Ihrig Reviewed-By: Chemi Atlow Reviewed-By: Benjamin Gruenbaum --- lib/internal/test_runner/mock/mock_timers.js | 3 +++ test/parallel/test-runner-mock-timers-date.js | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/lib/internal/test_runner/mock/mock_timers.js b/lib/internal/test_runner/mock/mock_timers.js index 66375c6688e038..c479f69ed0ddff 100644 --- a/lib/internal/test_runner/mock/mock_timers.js +++ b/lib/internal/test_runner/mock/mock_timers.js @@ -328,6 +328,9 @@ class MockTimers { #createDate() { kMock ??= Symbol('MockTimers'); const NativeDateConstructor = this.#nativeDateDescriptor.value; + if (NativeDateConstructor.isMock) { + throw new ERR_INVALID_STATE('Date is already being mocked!'); + } /** * Function to mock the Date constructor, treats cases as per ECMA-262 * and returns a Date object with a mocked implementation diff --git a/test/parallel/test-runner-mock-timers-date.js b/test/parallel/test-runner-mock-timers-date.js index ebd1e430be803f..7cee835eccaba3 100644 --- a/test/parallel/test-runner-mock-timers-date.js +++ b/test/parallel/test-runner-mock-timers-date.js @@ -117,4 +117,11 @@ describe('Mock Timers Date Test Suite', () => { assert.strictEqual(fn.mock.callCount(), 0); clearTimeout(id); }); + + it((t) => { + t.mock.timers.enable(); + t.test('should throw when a already-mocked Date is mocked', (t2) => { + assert.throws(() => t2.mock.timers.enable(), { code: 'ERR_INVALID_STATE' }); + }); + }); });