You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

fetch-mock无法Mock Fetch请求,仍调用真实URL问题咨询

Troubleshooting fetch-mock Not Intercepting Real Requests

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 */] });
      

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:42:20