Getting undefined with jest mock testing axios

Viewed 1148

What am I doing wrong here? I have been at this for a few days now and cant seem to figure out the issue with the code that I am trying to test.

Here is my call to the API:

import axios from 'axios';
import { environment } from '../environments/environment';
import { AppPersons } from './usersUtils';

const getData = (): Promise<AppPersons[]> => {
  const config = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('access_token')}`
    }
  };
  return axios
    .get(`${environment.userServiceURL}/persons`, config)
    .then(response => response.data._embedded.persons)
    .catch(err => {
      console.log(err);
    });
};
export default getData;

Here is my test:

import axios from 'axios';
import getData from '../utils/userData';

jest.mock('axios');

describe('user page page', () => {
  it('should fetch users', () => {
    const users = {
      _embedded: {
        person: [
          {
            role: {
              id: 1,
              roleName: 'Administrator',
              description: 'Administers the systems and user.'
            },
            active: true,
            email: 'user@test.com',
            firstName: 'Administrator',
            lastName: 'System',
            username: 'admin',
            id: 1,
            _links: {
              self: { href: 'http://users:8080/users/api/data/persons/1' },
              person: {
                href: 'http://users:8080/users/api/data/persons/1{?projection}',
                templated: true
              },
              role: { href: 'http://users:8080/users/api/data/persons/1/role' }
            }
          }
        ]
      }
    };

    const response = { data: users };

    axios.get.mockImplementation(() => Promise.resolve(response));
    return getData().then(resp => expect(resp).toEqual(users));
  });
});

The result:

Expected: {"_embedded": {"person": [{"_links": {"person": {"href": "http://users:8080/users/api/data/persons/1{?projection}", "templated": true}, "role": {"href": "http://users:8080/users/api/data/persons/1/role"}, "self": {"href": "http://users:8080/users/api/data/persons/1"}}, "active": true, "email": "user@test.com", "firstName": "Administrator", "id": 1, "lastName": "System", "role": {"description": "Administers the systems and user.", "id": 1, "roleName": "Administrator"}, "username": "admin"}]}}
Received: undefined

The received is constantly coming back with the undefined and I am struggling to understand why.

My first thoughts are maybe its the object that I am stubbing out but It looks like when I change it, the received is still not correct.

1 Answers

You should change the mocked response from users._embedded.person to users._embedded.persons. That's why you got undefined.

E.g.

getData.ts:

import axios from 'axios';
import { environment } from './environment';
import { AppPersons } from './usersUtils';

const getData = (): Promise<AppPersons[]> => {
  const config = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('access_token')}`,
    },
  };
  return axios
    .get(`${environment.userServiceURL}/persons`, config)
    .then((response) => response.data._embedded.persons)
    .catch((err) => {
      console.log(err);
    });
};
export default getData;

usersUtils.ts:

export interface AppPersons {}

environment.ts:

export const environment = {
  userServiceURL: '',
};

getData.test.ts:

import axios from 'axios';
import getData from './getData';

jest.mock('axios');

const maxios = axios as jest.Mocked<typeof axios>;

describe('user page page', () => {
  it('should fetch users', () => {
    const users = {
      _embedded: {
        persons: [
          {
            role: {
              id: 1,
              roleName: 'Administrator',
              description: 'Administers the systems and user.',
            },
            active: true,
            email: 'user@test.com',
            firstName: 'Administrator',
            lastName: 'System',
            username: 'admin',
            id: 1,
            _links: {
              self: { href: 'http://users:8080/users/api/data/persons/1' },
              person: {
                href: 'http://users:8080/users/api/data/persons/1{?projection}',
                templated: true,
              },
              role: { href: 'http://users:8080/users/api/data/persons/1/role' },
            },
          },
        ],
      },
    };

    const response = { data: users };

    maxios.get.mockResolvedValue(response);
    return getData().then((resp) => {
      expect(resp).toEqual(users._embedded.persons);
      expect(maxios.get).toBeCalledWith('/persons', {
        headers: {
          Authorization: `Bearer null`,
        },
      });
    });
  });
});

unit test result:

 PASS  examples/65280473/getData.test.ts
  user page page
    ✓ should fetch users (3 ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |   88.89 |      100 |   66.67 |   88.89 |                   
 environment.ts |     100 |      100 |     100 |     100 |                   
 getData.ts     |    87.5 |      100 |   66.67 |    87.5 | 15                
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.173 s

source code: https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/65280473

Related