Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

461
Vistas
Burlarse de axios e interceptores con Jest devuelve mockImplemetation undefined

Tengo esta implementación de axios:

 const api = axios.create({ baseURL: process.env.REACT_APP_BACKEND_URL, headers: { "content-type": "application/json" }, responseType: "json" }) function createAxiosRequestInterceptor(axiosInstance) { axiosInstance.interceptors.request.use( config => { const accessToken = localStorage.getItem(REACT_FE_ACCESS_TOKEN) if (accessToken) { config.headers.common.Authorization = `Bearer ${accessToken}` } return config } ) } function createAxiosResponseInterceptor(axiosInstance) { axiosInstance.interceptors.response.use( response => { return response; }, error => { return Promise.reject(error) } ) }

Esta es mi prueba:

 import React from 'react' import { Router } from 'react-router-dom' import { cleanup, render, wait } from '@testing-library/react' import { createMemoryHistory } from 'history' import axios from 'axios' import Dashboard from '../../pages/Dashboard' import AuthRouter from '../../../AuthRouter' import thunk from 'redux-thunk'; import configureMockStore from 'redux-mock-store'; function renderWithRouter( ui, { route = '/', history = createMemoryHistory({ initialEntries: [route] }), } = {} ) { const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); const store = mockStore(); return { ...render(<Router history={history}><AuthRouter type="private" store={store}>{ui}</AuthRouter></Router>), history, } } afterEach(cleanup) jest.mock('axios', () => { return { create: () => { return { interceptors: { request: {eject: jest.fn(), use: jest.fn()}, response: {eject: jest.fn(), use: jest.fn()}, }, }; }, }; }); describe('when unauthenticated', () => { axios.get.mockImplementation(() => Promise.resolve({ data: {error: 'user or password wrong'} })); const props = { isAuthenticated: false, } it('redirects when authToken invalid', async () => { const { history } = renderWithRouter(<Dashboard {...props} />) expect(history.location.pathname).toEqual('/') }) })

Obtengo: TypeError: Cannot read property 'mockImplementation' of undefined

Si cambio la implementación simulada de axios de la siguiente manera:

 jest.mock('axios')

Obtengo TypeError: Cannot read property 'interceptors' of undefined

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

¿Intentaste burlarte así?

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

Y en la prueba:

 mockAxios.get = jest.fn(() => Promise.resolve({ data: {error: 'user or password wrong'} }));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda