fetch-mock无法Mock Fetch请求,仍调用真实URL问题咨询
Hey there! I’ve run into this exact headache before—fetch-mock can feel like it’s ignoring your mocks for no reason, but usually it’s a small oversight. Let’s break down the most common fixes:
1. You didn’t properly replace the global fetch instance
fetch-mock works by overriding the global fetch function, but if this replacement doesn’t stick, your requests will still hit the real URL.
Node.js with
node-fetch: Either replace the global fetch or mock the module directly:// Option 1: Use fetch-mock's sandbox to override global fetch const fetchMock = require('fetch-mock').sandbox(); global.fetch = fetchMock; // Option 2: Mock the node-fetch module (Jest example) jest.mock('node-fetch', () => require('fetch-mock').sandbox());Browser/test environments (like Jest + jsdom): Enable mocks before your tests run:
import fetchMock from 'fetch-mock'; beforeEach(() => { fetchMock.enableMocks(); fetchMock.resetMocks(); // Clear old mocks between tests });
2. Your mock URL matching is too strict (or wrong)
If your mock’s URL doesn’t exactly match the actual request (including query params, trailing slashes, or case), fetch-mock will let the real request go through.
- Common mismatch: You mock
'/api/users'but your request is'/api/users?page=1'—the query params break the exact match. - Fixes:
- Use a regex to match partial URLs:
fetchMock.get(/\/api\/users/, { data: [] }); - Test with wildcard matching first to confirm mocking works:
// Catch all GET requests temporarily fetchMock.get('*', { status: 200, body: 'mocked response' }); - Explicitly include query params in your mock:
fetchMock.get('/api/users?page=1', { data: [/* mock data */] });
- Use a regex to match partial URLs:
3. The fetch request runs before your mock is set up
If your code fires fetch immediately (e.g., on module import, or in a component’s constructor before your test configures the mock), the real request will go out before fetch-mock can intercept it.
React/Vue component fix: Set up mocks first, then render the component:
test('fetches data on mount', async () => { // Configure mock first fetchMock.get('/api/data', { data: 'mocked' }); // Then render the component render(<MyDataComponent />); // Wait for the fetch to complete await waitFor(() => expect(fetchMock.called()).toBe(true)); });Module-level fetch fix: Wrap the fetch call in a function you can trigger after mocking, or use dependency injection to pass fetch into the module.
4. Your code uses a local fetch import instead of the global one
If your code does import fetch from 'node-fetch' (or a similar local import), fetch-mock’s global override won’t affect it—you need to mock the imported module directly.
- Jest example:
// Mock the node-fetch module entirely jest.mock('node-fetch', () => { const fetchMock = require('fetch-mock').sandbox(); return fetchMock; }); // Then in your test: import fetch from 'node-fetch'; fetch.get('/api/data', { data: 'mocked' });
5. Quick sanity check
Add a log in your test to verify if the mock is being hit:
console.log(fetchMock.calls()); // Should show your mock requests if they're intercepted
If none of these work, sharing a snippet of your test code and the actual fetch call would help pin down the issue!
内容的提问来源于stack exchange,提问作者Rafael Korbas

