V
V
Vadim2020-05-10 16:59:34
JavaScript
Vadim, 2020-05-10 16:59:34

How to test axios wrapper with Jest?

I can't figure out how to test and Jest my client to the server API.

I have createApiClient.js file :

import axios from 'axios';

function createApiClient(config = {}) {
  const client = axios.create(config);
  client.interceptors.response.use((response) => response.data,
    (error) => {
      if (error.response) {
        throw error.response.data;
      } else {
        throw new Error('Ошибка во время соединения с сервером! Попробуйте повторить попытку позже.');
      }
    });
  return client;
}
export default createApiClient;


Then there is a file already using this function to create a specific client client.js :
import createApiClient from '../createApiClient';

const request = createApiClient({
  baseURL: process.env.VUE_APP_AUTH_API_URL,
});
async function logIn(username, password) {
  const { token } = await request.post('login/', {
    username,
    password,
  });
  return token;
}
    // other functions...
export { logIn, register, getUserInfo };


How to test logIn () and other functions in the client, I can’t understand how and what to mock correctly, I’m especially interested in the moment with axios.create()and interceptors?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim, 2020-05-11
@vadimek

Solved a problem:

import { logIn } from '@/api/auth/client';
import createApiClientMock from '@/api/createApiClient';

jest.mock('@/api/createApiClient', () => {
  const axiosInstance = {
    post: jest.fn(),
    get: jest.fn(),
  };
  return jest.fn(() => axiosInstance);
});
const mRequest = createApiClientMock();

describe('Проверка клиента API аутентификации', () => {
  it('login success', async () => {
    const mResponse = { token: 'token' };
    mRequest.post.mockResolvedValueOnce(mResponse);
    const actual = await logIn('foo', 'qwerty');
    expect(actual).toEqual('token');
    expect(mRequest.post).toHaveBeenNthCalledWith(1, 'login/', { username: 'foo', password: 'qwerty' });
  });
});

Y
Yunus Gaziev, 2020-05-10
@BBoyJuss

https://www.robinwieruch.de/axios-jest

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question