diff --git a/test/common/gc.js b/test/common/gc.js index af637af7bedcd6..9860bb191ee072 100644 --- a/test/common/gc.js +++ b/test/common/gc.js @@ -1,5 +1,7 @@ 'use strict'; +const wait = require('timers/promises').setTimeout; + // TODO(joyeecheung): merge ongc.js and gcUntil from common/index.js // into this. @@ -65,6 +67,15 @@ async function checkIfCollectable( createObject(); } +// Repeat an operation and give GC some breathing room at every iteration. +async function runAndBreathe(fn, repeat, waitTime = 20) { + for (let i = 0; i < repeat; i++) { + await fn(); + await wait(waitTime); + } +} + module.exports = { checkIfCollectable, + runAndBreathe, }; diff --git a/test/parallel/test-shadow-realm-gc-module.js b/test/parallel/test-shadow-realm-gc-module.js index 7f822bdd52fe1d..6077bf03146d87 100644 --- a/test/parallel/test-shadow-realm-gc-module.js +++ b/test/parallel/test-shadow-realm-gc-module.js @@ -8,13 +8,11 @@ const common = require('../common'); const fixtures = require('../common/fixtures'); +const { runAndBreathe } = require('../common/gc'); -async function main() { - const mod = fixtures.fileURL('es-module-shadow-realm', 'state-counter.mjs'); - for (let i = 0; i < 100; i++) { - const realm = new ShadowRealm(); - await realm.importValue(mod, 'getCounter'); - } -} +const mod = fixtures.fileURL('es-module-shadow-realm', 'state-counter.mjs'); -main().then(common.mustCall()); +runAndBreathe(async () => { + const realm = new ShadowRealm(); + await realm.importValue(mod, 'getCounter'); +}, 100).then(common.mustCall()); diff --git a/test/parallel/test-shadow-realm-gc.js b/test/parallel/test-shadow-realm-gc.js index 83f793fd89222f..c6de4a32a88faa 100644 --- a/test/parallel/test-shadow-realm-gc.js +++ b/test/parallel/test-shadow-realm-gc.js @@ -6,14 +6,16 @@ */ const common = require('../common'); +const { runAndBreathe } = require('../common/gc'); const assert = require('assert'); const { isMainThread, Worker } = require('worker_threads'); -for (let i = 0; i < 100; i++) { +runAndBreathe(() => { const realm = new ShadowRealm(); realm.evaluate('new TextEncoder(); 1;'); -} +}, 100).then(common.mustCall()); +// Test it in worker too. if (isMainThread) { const worker = new Worker(__filename); worker.on('exit', common.mustCall((code) => {