fetch-mock未Mock请求却调用真实API,导入报错求助(Jest+Babel环境)
Hey there, let's break down and solve the two problems you're hitting with fetch-mock:
1. Mock isn't working (real API is being called instead)
This usually happens because fetch-mock isn't properly overriding the fetch instance your code is using. Here's how to fix it:
Check how you're using fetch in your code
- If your code relies on the global
fetch: You need to explicitly assign the fetch-mock sandbox toglobal.fetchbefore each test. - If you're importing
fetchfrom a module (likenode-fetch): You'll need to use Jest's mocking to replace that import with fetch-mock.
Example for global fetch
const fetchMock = require('fetch-mock/es5/server'); beforeEach(() => { // Reset mocks between tests to avoid cross-test contamination fetchMock.reset(); // Replace global fetch with fetch-mock's sandboxed instance global.fetch = fetchMock.sandbox(); }); test('should return mocked data instead of hitting real API', () => { // Set up your mock response global.fetch.get('/your-api-endpoint', [{ key: 'val1' }, { key: 'val2' }]); // Call your function that uses fetch return yourApiClient.getData().then(response => { // Verify you got the mocked data expect(response).toEqual([{ key: 'val1' }, { key: 'val2' }]); // Verify the mock was called (not the real API) expect(global.fetch.called('/your-api-endpoint')).toBe(true); }); });
Additional checks
- Double-check that the mock's URL exactly matches the URL your code is requesting (including base URLs, query params, or trailing slashes).
- Make sure you set up the mock before calling the function that triggers the fetch request.
2. Error when using fetch-mock instead of fetch-mock/es5/server
Node v6.13.0 has limited support for ES6+ syntax, and the main fetch-mock module uses modern ES6 exports that Node 6 can't parse without extra transpilation. The /es5/server entry is specifically compiled to ES5 for compatibility with older Node versions like yours.
Solution
Stick with require('fetch-mock/es5/server') (or import fetchMock from 'fetch-mock/es5/server' if your Babel is set up to handle it). Avoid importing the main fetch-mock module directly—this is the intended way to use fetch-mock with Node 6.
If you really want to use the main module, you'd need to configure Babel to transpile fetch-mock in your Jest settings, but this is more complex and unnecessary when the ES5 entry exists.
Final Notes
- Ensure you're using a version of fetch-mock that supports Node 6 (versions like v8.x are known to work; newer versions may drop support).
- Always reset your mocks between tests to prevent state leakage.
内容的提问来源于stack exchange,提问作者vamsiampolu

