I keep getting undefined error when running test on my API function
Expected: "Mock Jedi"
Received: undefined
12 | const result = await fetchAdmin();
13 | console.log(result);
> 14 | expect(result).toEqual('Mock Jedi');
| ^
15 | });
My API is in this file:
AdminTable.js
export const ADMIN_URL = '/admin_management/list/';
export const fetchAdmin = async () => {
try {
const response = await axios.post(
ADMIN_URL
);
return response.data.results;
} catch (err) {
console.log(`Error: ${err.message}`);
}
};
and my test file is like this:
app.test.js
import mockAxios from 'axios';
import { fetchAdmin } from '../pages/AdminTable';
jest.mock('axios');
mockAxios.post.mockResolvedValue({ data: { results: 'Mock Jedi' } });
describe('fetchAdmin', () => {
test('return data', async () => {
const result = await fetchAdmin();
console.log(result);
expect(result).toEqual('Mock Jedi');
});
});
I was expecting that the received results to also be "Mock Jedi" since the mock axios is set as
{ data: { results: 'Mock Jedi' } }
!!!FIXED!!!
First mistake i made was not letting jest.mock to do a post request. Changes to app.test.js
jest.mock('axios',()=>({
post: jst.fn(),
}));
But after implementing that there is a typeError: axios.create not a function
. Which lead me to my axios file
import axios from 'axios';
const BASE_URL = 'http://localhost:5000/';
export default axios.create({
baseURL: BASE_URL,
});
I then found the solution to mock jest based on my axios file instead. The changes were done to the test file
import { fetchAdmin } from '../pages/AdminTable';
import axios from '../api/axios';
jest.mock('../api/axios', () => ({
post: jest.fn(),
}));
mockAxios.post.mockResolvedValue({ data: { results: 'Mock Jedi' } });
describe('fetchAdmin', () => {
test('return correct data', async () => {
const result = await fetchAdmin();
expect(result).toMatch('Mock Jedi');
});
2
Answers
You’re creating a mock for
axios
but nothing foraxios.post
.I would recommend something like this
or if you’re using
axios.create()
somewhere in the pipeline…Now Jest knows that
mockAxios.post()
is mocked function and yourfetchAdmin
code will call it.You can also verify the call was made with the expected arguments with
You are returning
response.data.results
in yourfetchAdmin
function, but in your test, you are expecting the result to be ‘Mock Jedi’. Instead, you should expectresponse.data.results
to be equal to ‘Mock Jedi’.Use: