Testing API calls and network requests in Jest requires using mocks to isolate external dependencies:
1. Mock fetch API:
javascriptglobal.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:
javascriptimport 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:
javascripttest('handles API errors', async () => { axios.get.mockRejectedValue(new Error('Network Error')); await expect(getUser(1)).rejects.toThrow('Network Error'); });
5. Testing Different Response Statuses:
javascripttest('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):
javascriptimport { 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