Skip to content

Commit

Permalink
test: fix flaky test-timers-immediate-queue
Browse files Browse the repository at this point in the history
The test featured a timer for the purpose of measuring event loop
progess. Replacing it with a deterministic feature, such as a
`MessagePort`, removes the dependency on OS-specific timing
behaviour and thus makes the test no longer flaky.

Fixes: nodejs#24497
  • Loading branch information
addaleax committed Feb 1, 2020
1 parent 9528f95 commit e86098b
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions test/parallel/test-timers-immediate-queue.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
'use strict';
require('../common');
const assert = require('assert');
const { MessageChannel } = require('worker_threads');

// setImmediate should run clear its queued cbs once per event loop turn
// but immediates queued while processing the current queue should happen
Expand All @@ -30,18 +31,21 @@ const assert = require('assert');
// hit should be the exact same size of QUEUE, if we're letting things
// recursively add to the immediate QUEUE hit will be > QUEUE

// We use MessagePorts to figure out whether the event loop has progressed
// rather than timers because they are not subject to timer-precision-related
// flakiness, see https://github.com/nodejs/node/issues/24497 for details.
let ticked = false;
{
const { port1, port2 } = new MessageChannel();
port1.onmessage = () => ticked = true;
port1.unref();
port2.postMessage('');
}

let hit = 0;
const QUEUE = 10;

function run() {
if (hit === 0) {
setTimeout(() => { ticked = true; }, 1);
const now = Date.now();
while (Date.now() - now < 2);
}

if (ticked) return;

hit += 1;
Expand Down

0 comments on commit e86098b

Please sign in to comment.