» npm install axios-mock-adapter
» npm install @types/axios-mock-adapter
Two things to try here:
- Maybe you already have this elsewhere in your code, but be sure to set up mockAdaptor:
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mockAdapter = new MockAdapter(axios);
- I haven't found a way to get the mock adapter working when the function you are testing uses 'axios.create' to set up a new axios instance. Try something along the lines of this instead:
// api/index.js
const api = {
get(path) {
return axios.get('/api' + path)
.then((response) => {
return response.data;
});
}
}
export default api;
For anyone still struggling with this.
You need to make sure you iniatilise your MockAdapter outside a test body.
ie. Incorrect
it('should do a thing', () => {
const mockAdapter = new MockAdapter(axios);
})
Correct
const mockAdapter = new MockAdapter(axios);
it('should pass' () => {})
First of all: you have to use the same axios instance with both places: to setup the mock response and to make the actual call. When I want to mock some API I usually create and export the axios instance in a separate file, and just import it where I need it. like so:
// dataAPI.js
import axios from 'axios';
export const dataAPI = axios.create(); // general settings like baseURL can be set here
// FeatureTable.js
import React, { useEffect } from 'react';
import { dataAPI } from './dataAPI';
export const FeatureTable = () => {
useEffect(() => {
dataAPI.get('http://localhost:8080/users').then(something);
}, []);
return (<div>something</div>);
};
// mock.js
import { dataAPI } from './dataAPI';
import MockAdapter from 'axios-mock-adapter';
import { users } from './mockData.js'
const mock = new MockAdapter(dataAPI);
mock.onGet('http://localhost:8080/users').reply(200, users);
I want to point out axios-response-mock as an alternative to axios-mock-adapter. Disclaimer: I'm the author of that library. I was a bit frustrated by mock-adapter because I didn't find the API intuitive and it has limitations (e.g. can't match URL params in conjunction with POST requests) and that it would not let unmatched requests pass-through by default.
In your table file, you have to pass the relative path, not the absolute one.
const users = [{ id: 1, name: "John Smith" }];
const featureTable = (mock: any) => {
mock.onGet("/users").reply(200, users);
}
export default featureTable;
As library documentation explains, unmocked requests should be explicitly allowed:
// Mock specific requests, but let unmatched ones through
mock
.onGet('/foo').reply(200)
.onPut('/bar', { xyz: 'abc' }).reply(204)
.onAny().passThrough();
Adding to @Estus answer, we can forward other requests to server as below as well.
// Mock all requests to /foo with HTTP 200,
// but forward any others requests to server
var mock = new MockAdapter(axiosInstance, { onNoMatch: "passthrough" });
mock.onAny("/foo").reply(200);