Проверьте, вызывается ли диспетчерское действие в перехватчике axios, используя Jest - PullRequest
0 голосов
/ 22 октября 2019

Я хочу проверить, вызывается ли функция loginReset() каждый раз, когда возникает несанкционированный запрос или код состояния ответа 401.

Мой код следующий:

use-request. js

import axios from "axios"
import { axiosDefaultOptions } from "../config"
import { useSelector, useDispatch } from "react-redux"
import { loginReset } from "../store/reducers/login-slice"

const useRequest = (auth=false) => {
  const request = axios.create(axiosDefaultOptions)
  const dispatch = useDispatch()

  if(auth){
    const token = useSelector( state => state.login.data ? state.login.data.accessToken : null )
    request.interceptors.request.use(config => {
      config.headers.Authorization =  token ? `Bearer ${token}` : ''
      return config
    })  

    request.interceptors.response.use(response => {
      return response
    }, error => {
      if(error.response.status === 401) {
        dispatch(loginReset())
      }
      return Promise.reject(error)
    })
  }

  return request
}

export default useRequest

use-request.test.js

import { testHookwithStore } from "../utils"
import faker from "faker"
import { useRequest } from "../../components/hooks"
import configureStore from "redux-mock-store"
import MockAdapter from "axios-mock-adapter"
import { axiosDefaultOptions } from "../../components/config"
import thunk from "redux-thunk"


describe("useRequest", () => {

  faker.seed(123);
  let request = null
  let authRequest = null
  let token = faker.random.uuid()
  const mockStore = configureStore([thunk])
  let authRequestAdapter = null
  const fakeDomainWord = faker.internet.domainWord()
  const fakeUrl = `${axiosDefaultOptions.baseURL}/${fakeDomainWord}`

  beforeEach(() => {
    let store = mockStore({
      login: { data: { accessToken: token } }
    })
    testHookwithStore(store, () => {
      request = useRequest()
      authRequest = useRequest(true)

      authRequestAdapter = new MockAdapter(authRequest)
      authRequestAdapter.onPost(fakeDomainWord, {}).reply(401, { code: 401, message: "Bad credentials" })
    })
  })

  test("Request should have no headers", () => {
    request.interceptors.request.use( config => {
      expect(config.headers.Authorization).toBeNull()
    })
  })

  test("Auth request should have Authentication Headers", () => {
    authRequest.interceptors.request.use( config => {
      expect(config.headers.Authorization).toBe(`Bearer ${token}`)
    })
  })

  test("Auth request resets login when 401", async () => {
    const loginReset = jest.fn()
    try{
      await authRequest.post(fakeUrl, {})
    }
    catch(error){
      expect(loginReset).toHaveBeenCalledTimes(1)
    }
  })
})

testHookwithStore в основном просто создает компонент, обернутый вокруг провайдера. Последний тест не пройден, и я не уверен, как я могу проверить, действительно ли отправка работает. Любые подсказки здесь?

1 Ответ

0 голосов
/ 22 октября 2019

Видимо, в издевательском магазине есть функция getActions().

test("Auth request resets login when 401", async () => {
    try{
      await authRequest.post(fakeUrl, {})
    }
    catch(error){
      expect(store.getActions()[0].type).toBe("loginReset")
    }
})
...