skip to Main Content

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


  1. You’re creating a mock for axios but nothing for axios.post.

    I would recommend something like this

    jest.mock("axios", () => ({
      post: jest.fn(),
    }));
    

    or if you’re using axios.create() somewhere in the pipeline…

    jest.mock("axios", () => ({
      create: jest.fn(() => ({
        post: jest.fn(),
      })),
    }));
    

    Now Jest knows that mockAxios.post() is mocked function and your fetchAdmin code will call it.


    You can also verify the call was made with the expected arguments with

    expect(mockAxios.post).toHaveBeenCalledWith(ADMIN_URL);
    
    Login or Signup to reply.
  2. You are returning response.data.results in your fetchAdmin function, but in your test, you are expecting the result to be ‘Mock Jedi’. Instead, you should expect response.data.results to be equal to ‘Mock Jedi’.

    Use:

    expect(result).toEqual({ results: 'Mock Jedi' });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search