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

How to test axios interceptors using jest?

1个答案

1

When testing Axios interceptors in Jest, you can use several approaches to ensure the interceptors behave as expected. Here are the steps to test Axios interceptors with Jest:

  1. Mock Axios - In tests, you need to mock the Axios library to monitor the addition and invocation of interceptors.

  2. Add Interceptors - Configure your request or response interceptors in the test.

  3. Make a Request - Initiate a request using the mocked Axios.

  4. Verify Interceptor Behavior - Confirm that the interceptor modifies the request or response as expected.

  5. Cleanup - After the test, remove the interceptor to avoid side effects on other tests.

Here is a specific test case example demonstrating how to test a simple request interceptor that adds an Authorization header to each request:

javascript
// Import the relevant libraries and modules import axios from 'axios'; import { addAuthInterceptor } from './interceptors'; // Assume this is your interceptor module // Use jest.mock to mock axios jest.mock('axios'); describe('axios request interceptor', () => { it('should add an Authorization header', () => { // Set up the mock request const mockRequest = {}; axios.request.mockResolvedValue(mockRequest); // Add the interceptor const interceptorId = axios.interceptors.request.use(addAuthInterceptor); // Mock the interceptor implementation const token = 'faketoken123'; const addAuthInterceptor = (config) => { config.headers['Authorization'] = `Bearer ${token}`; return config; }; // Make a GET request axios.get('/someurl'); // Get the last called configuration object const lastCall = axios.request.mock.calls[0][0]; // Verify the Authorization header is added expect(lastCall.headers['Authorization']).toEqual(`Bearer ${token}`); // Cleanup the interceptor axios.interceptors.request.eject(interceptorId); }); });

In this example, we:

  • Assume an addAuthInterceptor function that adds an Authorization header to the request configuration.
  • Use jest.mock to mock axios and set up the mock request.
  • Call our interceptor function to add the interceptor to the Axios instance.
  • Initiate a GET request, at which point our interceptor should be triggered.
  • Use axios.request.mock.calls to retrieve the request configuration and verify that the Authorization header has been added.
  • At the end of the test, we use the axios.interceptors.request.eject method to remove the interceptor, ensuring it does not affect other tests.

Adjust this example based on your specific needs. For instance, if you have different interceptor logic, account for it when mocking the interceptor implementation. Additionally, if your interceptor is asynchronous, you may need to use async/await in your tests.

2024年6月29日 12:07 回复

你的答案