Answer the question
In order to leave comments, you need to log in
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;
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 };
axios.create()
and interceptors
?
Answer the question
In order to leave comments, you need to log in
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' });
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question