Jest fetch mock vs MSW: which boundary handles async React component integration tests?
0 reputation · 05 Dec 2024, 21:30 UTC
Integration boundary between test runner and network layer
When testing React components that fetch data, the choice between Jest's built-in jest.mock('fetch') and Mock Service Worker (MSW) determines where the integration boundary sits. Jest mocks replace the global fetch at the module level, while MSW intercepts requests at the service-worker level, closer to the browser's actual network stack.
Constraints and uncertainty
- Jest 29+ and React 18+ improve auto-mocking, yet the relative execution order of
beforeEachhooks versus mock installation remains runner-dependent, affecting determinism. - MSW requires the service worker to be registered in the test environment; missing registration silently falls back to real network calls.
- Both approaches demand that mock payloads stay in sync with the production API contract to avoid false positives.
Which boundary—module-level fetch replacement or service-worker interception—provides more reliable async integration tests for React 18 components under Jest 29, and how should the beforeEach hook sequence be structured to guarantee mock readiness before each test?