乐闻世界logo
搜索文章和话题

How to test API calls and network requests in Jest? How to mock fetch and Axios?

2月19日 19:55

Testing API calls and network requests in Jest requires using mocks to isolate external dependencies:

1. Mock fetch API:

javascript
global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({ data: 'test' }) }) ); test('fetches data from API', async () => { const data = await fetchData(); expect(data).toEqual({ data: 'test' }); expect(fetch).toHaveBeenCalledTimes(1); });

2. Mock Axios:

javascript
import axios from 'axios'; jest.mock('axios'); test('fetches user data', async () => { const mockData = { name: 'John', age: 30 }; axios.get.mockResolvedValue({ data: mockData }); const result = await getUser(1); expect(result).toEqual(mockData); expect(axios.get).toHaveBeenCalledWith('/users/1'); });

3. Mock Module Exports:

javascript
// api.js export const fetchData = () => fetch('/api/data'); // api.test.js import { fetchData } from './api'; import fetch from 'node-fetch'; jest.mock('node-fetch'); test('fetches data', async () => { fetch.mockResolvedValue({ json: () => ({ data: 'test' }) }); const result = await fetchData(); expect(result).toEqual({ data: 'test' }); });

4. Testing Error Handling:

javascript
test('handles API errors', async () => { axios.get.mockRejectedValue(new Error('Network Error')); await expect(getUser(1)).rejects.toThrow('Network Error'); });

5. Testing Different Response Statuses:

javascript
test('handles 404 error', async () => { axios.get.mockRejectedValue({ response: { status: 404, data: { message: 'Not found' } } }); await expect(getUser(1)).rejects.toMatchObject({ response: { status: 404 } }); });

6. Using MSW (Mock Service Worker):

javascript
import { rest } from 'msw'; import { setupServer } from 'msw/node'; const server = setupServer( rest.get('/api/users', (req, res, ctx) => { return res(ctx.json({ name: 'John' })); }) ); beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); test('fetches user with MSW', async () => { const user = await fetchUser(); expect(user).toEqual({ name: 'John' }); });

Best Practices:

  • Use mocks to isolate external API dependencies
  • Test both success and failure scenarios
  • Verify request parameters and response handling
  • Clean up mocks to avoid test pollution
  • Consider using MSW for more realistic API simulation
标签:AxiosJest