Skip to content

Commit 284e496

Browse files
test_runner: add ref methods to mocked timers
Fixes: #51701
1 parent 0550bc1 commit 284e496

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

lib/internal/test_runner/mock/mock_timers.js

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,14 +260,49 @@ class MockTimers {
260260

261261
#createTimer(isInterval, callback, delay, ...args) {
262262
const timerId = this.#currentTimer++;
263-
const timer = {
263+
class Timeout {
264+
constructor(opts) {
265+
this.id = opts.id;
266+
this.callback = opts.callback;
267+
this.runAt = opts.runAt;
268+
this.interval = opts.interval;
269+
this.args = opts.args;
270+
271+
ObjectDefineProperty(Timeout.prototype, 'hasRef', {
272+
__proto__: null,
273+
enumerable: false,
274+
value: () => true,
275+
});
276+
277+
ObjectDefineProperty(Timeout.prototype, 'ref', {
278+
__proto__: null,
279+
enumerable: false,
280+
value: () => this,
281+
});
282+
283+
284+
ObjectDefineProperty(Timeout.prototype, 'unref', {
285+
__proto__: null,
286+
enumerable: false,
287+
value: () => this,
288+
});
289+
290+
ObjectDefineProperty(Timeout.prototype, 'refresh', {
291+
__proto__: null,
292+
enumerable: false,
293+
value: () => this,
294+
});
295+
}
296+
}
297+
const opts = {
264298
__proto__: null,
265299
id: timerId,
266300
callback,
267301
runAt: this.#now + delay,
268302
interval: isInterval ? delay : undefined,
269303
args,
270304
};
305+
const timer = new Timeout(opts);
271306
this.#executionQueue.insert(timer);
272307
return timer;
273308
}

test/parallel/test-runner-mock-timers.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -844,4 +844,38 @@ describe('Mock Timers Test Suite', () => {
844844
clearTimeout(id);
845845
});
846846
});
847+
848+
describe('Api should have same public properties as original', () => {
849+
it('should have hasRef', (t) => {
850+
t.mock.timers.enable();
851+
const timer = setTimeout();
852+
assert.strictEqual(typeof timer.hasRef, 'function');
853+
assert.strictEqual(timer.hasRef(), true);
854+
clearTimeout(timer);
855+
});
856+
857+
it('should have ref', (t) => {
858+
t.mock.timers.enable();
859+
const timer = setTimeout();
860+
assert.ok(typeof timer.ref === 'function');
861+
assert.deepStrictEqual(timer.ref(), timer);
862+
clearTimeout(timer);
863+
});
864+
865+
it('should have unref', (t) => {
866+
t.mock.timers.enable();
867+
const timer = setTimeout();
868+
assert.ok(typeof timer.unref === 'function');
869+
assert.deepStrictEqual(timer.unref(), timer);
870+
clearTimeout(timer);
871+
});
872+
873+
it('should have refresh', (t) => {
874+
t.mock.timers.enable();
875+
const timer = setTimeout();
876+
assert.ok(typeof timer.refresh === 'function');
877+
assert.deepStrictEqual(timer.refresh(), timer);
878+
clearTimeout(timer);
879+
});
880+
});
847881
});

0 commit comments

Comments
 (0)