@MaksimOstr

При тестировании запроса Axios с помощью Jest в результате получаю undefined, как решить?

auth.test.ts

import axios from "axios"
import AuthService from "../feature-login/auth/service/AuthService"

jest.mock('axios', () => {
  return {
    create: jest.fn(() => ({
      post: jest.fn(),
      get: jest.fn(),
      interceptors: {
        request: { use: jest.fn(), eject: jest.fn() },
        response: { use: jest.fn(), eject: jest.fn() }
      }
    }))
  }
})

it('login-test', async () => {
      
        axios.post = jest.fn().mockResolvedValue({ data: 'dasfsdf' })

        const result = await AuthService.login({ username: 'Максим', password: 'masterkey' });

        console.log(result)
})


AuthService.ts

import { AxiosResponse } from "axios";
import { AuthResponse, IUser } from "../types/AuthResponse";
import $api from "../../../../../shared/src/http";

export default class AuthService {
    static async login(user: IUser): Promise<AxiosResponse<AuthResponse>> {
        return await $api.post<AuthResponse>('/auth/login', user)
    }
    static async checkAuth(): Promise<AxiosResponse<AuthResponse>> {
        return await $api.get<AuthResponse>('/auth/refresh', { withCredentials: true })
    }
}


index.ts (Место нахождения $api)

import axios from 'axios'
import { AuthResponse } from '../../../authentication/src/feature-login/auth/types/AuthResponse'

export const API_URL = 'http://localhost:3000/api'

const $api = axios.create({
    withCredentials: true,
    baseURL: API_URL
})

$api.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`
    return config;
})

$api.interceptors.response.use((config) => {
    return config
}, async (error) => {
    const isAuth = localStorage.getItem('token')
    const originalRequest = error.config
    if(error.response.status == 401 && isAuth && !error.config._isRetry && error.config) {
        originalRequest._isRetry = true
        try {
            const response = await axios.get<AuthResponse>(`${API_URL}/auth/refresh`, { withCredentials: true })
            localStorage.setItem('token', response.data.access_token)
            return $api.request(originalRequest)
        } catch (e) {
            console.log('Пользователь не авторизован')
        }
    }
    throw error
})

export default $api


Результат теста

650db79469810790114463.png

Я новичок в unit - тестировании и не знаю в чём может быть причина

Буду очень благодарен за помощь в решении данного вопроса!
  • Вопрос задан
  • 154 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы