Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

A mocked axios call in Jest returns undefined or never resolves

ErrorTypeError: 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.

  • Applies to Jest 30, axios 1, React 19
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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.*
  2. 2Match what you see, then jump to its fix

    1. 1Cannot 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. 2Cannot 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. 3Cannot read properties of undefined (reading 'items'), while the mock itself clearly returns somethingThe fixture is missing the data wrapperFix
    4. 4The test passes with no assertion running, or the result shows up after the test is already marked doneThe test ends before the promise settlesFix

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" src

2Fix

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.js

Confirmed by jestjs.io

Did this fix it?

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

Did this fix it?

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.js

Confirmed by jestjs.io

Did this fix it?

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.js

Confirmed by jestjs.io

Did this fix it?

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:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.