From 6cb8a60bcc535f5a73ef981bc5340a508b65c30d Mon Sep 17 00:00:00 2001 From: Marco Ippolito Date: Mon, 26 Feb 2024 16:57:05 +0100 Subject: [PATCH] test_runner: add ref methods to mocked timers Fixes: https://github.com/nodejs/node/issues/51701 PR-URL: https://github.com/nodejs/node/pull/51809 Reviewed-By: Chemi Atlow Reviewed-By: Moshe Atlow Reviewed-By: Tierney Cyren --- lib/internal/test_runner/mock/mock_timers.js | 30 ++++++++++++++++- test/parallel/test-runner-mock-timers.js | 34 ++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/lib/internal/test_runner/mock/mock_timers.js b/lib/internal/test_runner/mock/mock_timers.js index 00fe29d43c97ad..fa4c13a5dec6dc 100644 --- a/lib/internal/test_runner/mock/mock_timers.js +++ b/lib/internal/test_runner/mock/mock_timers.js @@ -67,6 +67,32 @@ const TIMERS_DEFAULT_INTERVAL = { setImmediate: -1, }; +class Timeout { + constructor(opts) { + this.id = opts.id; + this.callback = opts.callback; + this.runAt = opts.runAt; + this.interval = opts.interval; + this.args = opts.args; + } + + hasRef() { + return true; + } + + ref() { + return this; + } + + unref() { + return this; + } + + refresh() { + return this; + } +} + class MockTimers { #realSetTimeout; #realClearTimeout; @@ -260,7 +286,7 @@ class MockTimers { #createTimer(isInterval, callback, delay, ...args) { const timerId = this.#currentTimer++; - const timer = { + const opts = { __proto__: null, id: timerId, callback, @@ -268,6 +294,8 @@ class MockTimers { interval: isInterval ? delay : undefined, args, }; + + const timer = new Timeout(opts); this.#executionQueue.insert(timer); return timer; } diff --git a/test/parallel/test-runner-mock-timers.js b/test/parallel/test-runner-mock-timers.js index 7e519e8a2ad2fb..9af58d5cab0008 100644 --- a/test/parallel/test-runner-mock-timers.js +++ b/test/parallel/test-runner-mock-timers.js @@ -844,4 +844,38 @@ describe('Mock Timers Test Suite', () => { clearTimeout(id); }); }); + + describe('Api should have same public properties as original', () => { + it('should have hasRef', (t) => { + t.mock.timers.enable(); + const timer = setTimeout(); + assert.strictEqual(typeof timer.hasRef, 'function'); + assert.strictEqual(timer.hasRef(), true); + clearTimeout(timer); + }); + + it('should have ref', (t) => { + t.mock.timers.enable(); + const timer = setTimeout(); + assert.ok(typeof timer.ref === 'function'); + assert.deepStrictEqual(timer.ref(), timer); + clearTimeout(timer); + }); + + it('should have unref', (t) => { + t.mock.timers.enable(); + const timer = setTimeout(); + assert.ok(typeof timer.unref === 'function'); + assert.deepStrictEqual(timer.unref(), timer); + clearTimeout(timer); + }); + + it('should have refresh', (t) => { + t.mock.timers.enable(); + const timer = setTimeout(); + assert.ok(typeof timer.refresh === 'function'); + assert.deepStrictEqual(timer.refresh(), timer); + clearTimeout(timer); + }); + }); });