dimanche 13 décembre 2020

Getting undefined with jest mock testing axios

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 userData 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 userData().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.

Aucun commentaire:

Enregistrer un commentaire