A mocked axios call in Jest returns undefined or never resolves
TypeError: Cannot read properties of undefined (reading 'get')Short answer
After jest.mock('axios') every axios function is an empty mock that returns undefined until you give it a value. The test breaks when your code uses an instance from axios.create, calls a different method than the one you mocked, reads response.data from a value without the data wrapper, or finishes before the promise settles. Match the mock to the exact call.
Fix it fast
1Find out which cause you have
Look at how the code under test reaches axios, and put that next to what the test mocks. The name in the TypeError, get, data or then, shows which side of the call came back undefined.
grep -rn "axios" src --include=*.js --include=*.ts --include=*.tsx --exclude=*.test.*2Match what you see, then jump to its fix
- 1
Cannot read properties of undefined (reading 'get') as soon as the module is imported or the first call runsThe code uses an instance made with axios.createFix - 2
Cannot read properties of undefined (reading 'then'), or the real value never arrives although axios.get is mockedThe mock is set on a different method than the one the code callsFix - 3
Cannot read properties of undefined (reading 'items'), while the mock itself clearly returns somethingThe fixture is missing the data wrapperFix - 4
The test passes with no assertion running, or the result shows up after the test is already marked doneThe test ends before the promise settlesFix
- 1
What does the error look like?
TypeError: Cannot read properties of undefined (reading 'get')TypeError: Cannot read properties of undefined (reading 'data')TypeError: Cannot read properties of undefined (reading 'then')
Cause 1 of 4
The code uses an instance made with axios.create
1Check
jest.mock('axios') replaces axios.create with a mock function. A mocked function returns undefined unless told otherwise, so const client = axios.create(...) is undefined and mocking axios.get has no effect on it.
grep -rn "axios.create" src2Fix
Create the instance in one small module and mock that module, not axios. The automatic mock keeps the shape of the instance, so you can set return values on its methods.
// src/api/client.js
import axios from 'axios';
export const client = axios.create({ baseURL: '/api' });
// src/users.test.js
import { client } from './api/client';
import { getUsers } from './users';
jest.mock('./api/client');
test('returns the users', async () => {
client.get.mockResolvedValue({ data: [{ name: 'Bob' }] });
await expect(getUsers()).resolves.toEqual([{ name: 'Bob' }]);
});3Verify
Run the test file. The import no longer throws and the call returns your fixture.
npx jest src/users.test.jsConfirmed by jestjs.io
Cause 2 of 4
The mock is set on a different method than the one the code calls
1Check
Every function on an automatically mocked module returns undefined by default. If the code calls axios.post, or calls axios(config) directly, the get mock is never used.
grep -rnE "axios\.(get|post|put|patch|delete)|axios\(" src --exclude=*.test.*2Fix
Set the resolved value on the exact function that the code calls.
jest.mock('axios');
// code calls axios.post(url, body)
axios.post.mockResolvedValue({ data: { id: 1 } });
// code calls axios({ url, method })
axios.mockResolvedValue({ data: { id: 1 } });3Verify
Assert that the mock was used, so a wrong guess fails loudly.
expect(axios.post).toHaveBeenCalledWith('/users', { name: 'Bob' });Confirmed by jestjs.io
Cause 3 of 4
The fixture is missing the data wrapper
1Check
Code written for axios reads the body from response.data, and the Jest guide's own example mocks a value shaped { data: users }. If the test returns { items: [...] } directly, response.data is undefined and the next property read throws.
grep -rn "\.data" src --exclude=*.test.*2Fix
Shape the mocked value like a response: the payload goes under data, as in the Jest guide's example.
const resp = { data: { items: [1, 2, 3] } };
axios.get.mockResolvedValue(resp);3Verify
Run the test. The code under test now reads the items.
npx jest src/users.test.jsConfirmed by jestjs.io
Cause 4 of 4
The test ends before the promise settles
1Check
The Jest docs say the assertion for a promise must be returned. A test that neither returns nor awaits the call can finish before the assertion has any say, and expect.assertions exists to catch exactly that slip.
grep -rn "mockResolvedValue" src --include=*.test.*2Fix
Make the test async and await the call. Add expect.assertions so a skipped assertion fails the test.
test('loads users', async () => {
expect.assertions(1);
axios.get.mockResolvedValue({ data: [{ name: 'Bob' }] });
const users = await getUsers();
expect(users).toEqual([{ name: 'Bob' }]);
});3Verify
Change the expected value on purpose and confirm the test now fails, then change it back.
npx jest src/users.test.jsConfirmed by jestjs.io
How do I stop it coming back?
- Keep axios.create in a single module, and mock that module in tests.
- Write fixtures in the shape the code reads: { data: ... } for a success, and a rejected value for a failure.
- Start every async test with expect.assertions(n), so an assertion that never runs fails.
- Assert on toHaveBeenCalledWith for the URL and body, so the test also proves the right call was made.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
jest.mock() works at the top of the file but not inside a test
Mock works in one test and returns undefined in the next
Jest hoists jest.mock() only to the top of its own code block.
3 causes, each with a fixWeb apps
TypeScript says mockResolvedValue does not exist on an axios or fetch function
Property 'mockResolvedValue' does not exist on type '<T = any, R = AxiosResponse<T, any>, D = any>(url: string, config?: AxiosRequestConfig<D>) => Promise<R>'
TypeScript sees axios.get as a normal function, not a Jest mock, so it has no mockResolvedValue.
3 causes, each with a fixWeb apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fix