Skip to content

Commit

Permalink
test_runner: add ref methods to mocked timers
Browse files Browse the repository at this point in the history
Fixes: #51701
  • Loading branch information
marco-ippolito committed Feb 19, 2024
1 parent 0550bc1 commit 284e496
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
37 changes: 36 additions & 1 deletion lib/internal/test_runner/mock/mock_timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,14 +260,49 @@ class MockTimers {

#createTimer(isInterval, callback, delay, ...args) {
const timerId = this.#currentTimer++;
const timer = {
class Timeout {
constructor(opts) {
this.id = opts.id;
this.callback = opts.callback;
this.runAt = opts.runAt;
this.interval = opts.interval;
this.args = opts.args;

ObjectDefineProperty(Timeout.prototype, 'hasRef', {
__proto__: null,
enumerable: false,
value: () => true,
});

ObjectDefineProperty(Timeout.prototype, 'ref', {
__proto__: null,
enumerable: false,
value: () => this,
});


ObjectDefineProperty(Timeout.prototype, 'unref', {
__proto__: null,
enumerable: false,
value: () => this,
});

ObjectDefineProperty(Timeout.prototype, 'refresh', {
__proto__: null,
enumerable: false,
value: () => this,
});
}
}
const opts = {
__proto__: null,
id: timerId,
callback,
runAt: this.#now + delay,
interval: isInterval ? delay : undefined,
args,
};
const timer = new Timeout(opts);
this.#executionQueue.insert(timer);
return timer;
}
Expand Down
34 changes: 34 additions & 0 deletions test/parallel/test-runner-mock-timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});

0 comments on commit 284e496

Please sign in to comment.