From 31316b348a1a33eb4991e7fc4b4c5c60f46b0766 Mon Sep 17 00:00:00 2001 From: Tobias Bieniek Date: Thu, 11 Sep 2025 15:55:54 +0200 Subject: [PATCH] msw: Avoid unnecessary setup and teardown Instead of creating, starting and tearing down the worker for each test module, we can create it once, start it once for the full test suite and then tear it down at the end of the test suite. This also ensures that we don't accidentally perform network calls in tests that didn't explicitly set up MSW. Additionally, this might fix the flakiness we've been seeing with the test suite when run on the CI runners, and is generally recommended by the MSW devs. --- tests/helpers/setup-msw.js | 26 ++++++++++++++------------ tests/test-helper.js | 2 ++ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/tests/helpers/setup-msw.js b/tests/helpers/setup-msw.js index 364a36de7ef..ea0211b8e87 100644 --- a/tests/helpers/setup-msw.js +++ b/tests/helpers/setup-msw.js @@ -6,22 +6,24 @@ import { setupWorker } from 'msw/browser'; import { setupFakeTimers } from './fake-timers'; +const worker = setupWorker( + ...handlers, + http.get('/assets/*', passthrough), + http.all(/.*\/percy\/.*/, passthrough), + http.get('https://:avatars.githubusercontent.com/u/:id', passthrough), +); + +export function registerQUnitCallbacks(QUnit) { + QUnit.begin(() => worker.start({ quiet: true, onUnhandledRequest: 'error' })); + QUnit.testDone(() => worker.resetHandlers()); + QUnit.testDone(() => db.reset()); + QUnit.done(() => worker.stop()); +} + export default function (hooks) { setupWindowMock(hooks); setupFakeTimers(hooks, '2017-11-20T12:00:00'); - let worker = setupWorker( - ...handlers, - http.get('/assets/*', passthrough), - http.all(/.*\/percy\/.*/, passthrough), - http.get('https://:avatars.githubusercontent.com/u/:id', passthrough), - ); - - hooks.before(() => worker.start({ quiet: true, onUnhandledRequest: 'error' })); - hooks.afterEach(() => worker.resetHandlers()); - hooks.afterEach(() => db.reset()); - hooks.after(() => worker.stop()); - hooks.beforeEach(function () { this.worker = worker; this.db = db; diff --git a/tests/test-helper.js b/tests/test-helper.js index 455b56dc72d..14c46c66cb2 100644 --- a/tests/test-helper.js +++ b/tests/test-helper.js @@ -8,9 +8,11 @@ import { setup } from 'qunit-dom'; import Application from '../app'; import config from '../config/environment'; import registerMatchJsonAssertion from './helpers/match-json'; +import { registerQUnitCallbacks } from './helpers/setup-msw'; setup(QUnit.assert); registerMatchJsonAssertion(QUnit.assert); +registerQUnitCallbacks(QUnit); setApplication(Application.create(config.APP));