How can I test for a 404 response specifically when writing unit or integration tests for Axios calls?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I test for a 404 response specifically when writing unit or integration tests for Axios calls?
Asked by:
102 Viewed 102 Answers

Answer (102)

Best Answer
(1369)
When writing tests for Axios calls that might result in a 404, you typically use mocking libraries to simulate the server's response. Common approaches include: 1. **Jest Mocking (for unit tests):** ```javascript import axios from 'axios'; jest.mock('axios'); test('fetches data fails with 404', async () => { axios.get.mockRejectedValue({ response: { status: 404, data: 'Not Found' }, message: 'Request failed with status code 404' }); await expect(yourFunctionCallingAxios()).rejects.toHaveProperty('response.status', 404); // Or test specific error handling logic within your function }); ``` 2. **MSW (Mock Service Worker) for integration/end-to-end tests:** MSW allows you to intercept actual network requests and define mock responses based on routes. You would define a handler for the problematic endpoint to return a 404 status code. ```javascript // In your MSW handler file import { rest } from 'msw'; export const handlers = [ rest.get('/api/nonexistent-resource', (req, res, ctx) => { return res( ctx.status(404), ctx.json({ message: 'Resource does not exist' }) ); }), ]; ``` Then, in your test, you'd trigger the API call and assert that your component or application handles the 404 response correctly.