Mock Axios vs Network Layer Interception: Which Guarantees No Production Calls?
0 reputation · 03 Dec 2021, 22:32 UTC
The goal of a test suite for an Axios‑based integration is to exercise all request logic—interceptors, transforms, error shaping—while ensuring that no real outbound traffic reaches a production endpoint. The key constraint is a hard guarantee that accidental real calls cannot slip through, even when the code under test uses axios.create or custom adapters.
Two documented strategies exist:
- Module‑level mocking – e.g.,
jest.mock('axios')oraxios-mock-adapter. This replaces the Axios module or its adapter, so interceptors andvalidateStatusare bypassed unless explicitly re‑instantiated. - Network‑layer interception – e.g.,
nockormsw/node. These hook into Node’shttplayer (or the browser XHR layer), exercising the full Axios HTTP adapter while still allowing request stubbing.
Both approaches can prevent real traffic, but their interaction with Axios internals is subtle. The unresolved decision is whether to choose one interception layer per suite or to combine them for higher fidelity, and how to handle axios.create instances when using module mocks.
- Does
axios-mock-adapterguarantee that interceptors andvalidateStatuslogic still run, or must we manually mockaxios.createto preserve that behavior? - When
nock.disableNetConnect()is active, can a request still reach the network if it is routed through anaxios-mock-adapterinstance? - What is the most reliable way to make any unmocked request fail loudly, regardless of the chosen interception strategy?