Skip to content

Commit 09c417e

Browse files
committed
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.
1 parent 03afc7c commit 09c417e

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

tests/helpers/setup-msw.js

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,24 @@ import { setupWorker } from 'msw/browser';
66

77
import { setupFakeTimers } from './fake-timers';
88

9+
const worker = setupWorker(
10+
...handlers,
11+
http.get('/assets/*', passthrough),
12+
http.all(/.*\/percy\/.*/, passthrough),
13+
http.get('https://:avatars.githubusercontent.com/u/:id', passthrough),
14+
);
15+
16+
export function registerQUnitCallbacks(QUnit) {
17+
QUnit.begin(() => worker.start({ quiet: true, onUnhandledRequest: 'error' }));
18+
QUnit.testDone(() => worker.resetHandlers());
19+
QUnit.testDone(() => db.reset());
20+
QUnit.done(() => worker.stop());
21+
}
22+
923
export default function (hooks) {
1024
setupWindowMock(hooks);
1125
setupFakeTimers(hooks, '2017-11-20T12:00:00');
1226

13-
let worker = setupWorker(
14-
...handlers,
15-
http.get('/assets/*', passthrough),
16-
http.all(/.*\/percy\/.*/, passthrough),
17-
http.get('https://:avatars.githubusercontent.com/u/:id', passthrough),
18-
);
19-
20-
hooks.before(() => worker.start({ quiet: true, onUnhandledRequest: 'error' }));
21-
hooks.afterEach(() => worker.resetHandlers());
22-
hooks.afterEach(() => db.reset());
23-
hooks.after(() => worker.stop());
24-
2527
hooks.beforeEach(function () {
2628
this.worker = worker;
2729
this.db = db;

tests/test-helper.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ import { setup } from 'qunit-dom';
88
import Application from '../app';
99
import config from '../config/environment';
1010
import registerMatchJsonAssertion from './helpers/match-json';
11+
import { registerQUnitCallbacks } from './helpers/setup-msw';
1112

1213
setup(QUnit.assert);
1314
registerMatchJsonAssertion(QUnit.assert);
15+
registerQUnitCallbacks(QUnit);
1416

1517
setApplication(Application.create(config.APP));
1618

0 commit comments

Comments
 (0)