Mocking API Requests
When testing components that make API requests, it's important to mock those requests. This ensures that the tests are isolated and do not rely on external dependencies such as a live API server.
One common way to mock API requests is by using a library like Axios and its mock adapter feature.
Here's an example of how to mock an API request using Axios and the Jest testing library:
JAVASCRIPT
1import axios from 'axios';
2import MockAdapter from 'axios-mock-adapter';
3
4// Create a new instance of the mock adapter
5const mock = new MockAdapter(axios);
6
7// Mock a successful API response
8mock.onGet('/api/users').reply(200, [
9 { id: 1, name: 'John Doe' },
10 { id: 2, name: 'Jane Smith' },
11]);
12
13// Make the API request
14axios.get('/api/users')
15 .then((response) => {
16 // Handle the response
17 console.log(response.data);
18 })
19 .catch((error) => {
20 // Handle any errors
21 console.error(error);
22 });xxxxxxxxxx35
});// Mocking API requests// In order to test components that make API requests,// it's important to mock those requests. This ensures// that the tests are isolated and do not rely on external// dependencies such as a live API server.// One common way to mock API requests is by using a library// like `Axios` and its mock adapter feature.// Here's an example of how to mock an API request using// Axios and the Jest testing library:import axios from 'axios';import MockAdapter from 'axios-mock-adapter';// Create a new instance of the mock adapterconst mock = new MockAdapter(axios);// Mock a successful API responsemock.onGet('/api/users').reply(200, [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Smith' },]);// Make the API requestaxios.get('/api/users') .then((response) => { // Handle the responseOUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment



