0

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, axios.create)

    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

Результат выполнения теста1

7
  • вместо удаления и дублирования вопроса достаточно было просто отредактировать существующий вопрос.
    – Grundy
    18 сен в 20:41
  • Он был удалён без возможности редактирования, извиняюсь, я новичок на stackoverflow 18 сен в 20:50
  • значение задаешь методу статическому в глобальном объекте, а внутри api используешь instance
    – Grundy
    18 сен в 21:04
  • либо сохрани где-то то что в инициализации используешь post: jest.fn(), чтобы потом к этой функции обращаться, либо используй статические члены напрямую из axios а не после axios.create({
    – Grundy
    18 сен в 21:05
  • мне бы желательно расписать 21 сен в 17:00

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Посмотрите другие вопросы с метками или задайте свой вопрос.