Reputation: 11069
I created an axios instance ...
// api/index.js
const api = axios.create({
baseURL: '/api/',
timeout: 2500,
headers: { Accept: 'application/json' },
});
export default api;
And severals modules use it ..
// api/versions.js
import api from './api';
export function getVersions() {
return api.get('/versions');
}
I try to test like ..
// Test
import { getVersions } from './api/versions';
const versions= [{ id: 1, desc: 'v1' }, { id: 2, desc: 'v2' }];
mockAdapter.onGet('/versions').reply(200, versions);
getVersions.then((resp) => { // resp is UNDEFINED?
expect(resp.data).toEqual(versions);
done();
});
Why resp is undefined?
Upvotes: 10
Views: 14612
Reputation: 459
This is because you have not created a new instance of new MockAdapter
import { getVersions } from "./api/versions";
import api from "./api/index";
describe("getVersions", () => {
const versions = [
{ id: 1, desc: "v1" },
{ id: 2, desc: "v2" },
];
const mockClient = new MockAdapter(api);
it("should return status 200 and data === versions", async () => {
mockClient.onGet("/versions").reply(200, versions);
const result = await getVersions();
expect(result.status).toBe(200);
expect(result.data).toEqual(versions);
});
});
Attention!!! It is important in your case to create a new MockAdapter(api) using the api. If you create a MockAdapter(axios) will not work, this is a very common error. Because you are not using axios directly, but creating a new instance of axios
// api/index.js
const api = axios.create({
baseURL: '/api/',
timeout: 2500,
headers: { Accept: 'application/json' },
});
export default api;
Upvotes: 2
Reputation: 7555
You don't need axios-mock-adapter
. Here is how I mock my axios
:
// src/__mocks__/axios.ts
const mockAxios = jest.genMockFromModule('axios')
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios
Upvotes: -4
Reputation: 1634
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' () => {})
Upvotes: 3
Reputation:
according to James M. advice, I updated my api/index.js , not using the axios.create...
api/index.js
import http from 'axios'
export default {
fetchShoppingLists: () => {
console.log('API FETCH SHOPPINGLISTS')
return http
.get('http://localhost:3000/shoppinglists')
.then(response => {
return response
})
.catch(error => {
console.log('FETCH ERROR: ', error)
})
}
}
Upvotes: -1
Reputation: 183
Two things to try here:
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mockAdapter = new MockAdapter(axios);
// api/index.js
const api = {
get(path) {
return axios.get('/api' + path)
.then((response) => {
return response.data;
});
}
}
export default api;
Upvotes: 5