Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

470
Visualizações
Mocking axios and interceptors with Jest returns mockImplemetation undefined

I have this axios implementation:

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)
        }
    )
}

This is my test:

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('/')

    })
  })

I get: TypeError: Cannot read property 'mockImplementation' of undefined

If I change the mock implementation of axios as following:

jest.mock('axios')

I get TypeError: Cannot read property 'interceptors' of undefined

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Did you try to mock like this?

const mockAxios = {
   interceptors: {
      request: {eject: jest.fn(), use: jest.fn()},
      response: {eject: jest.fn(), use: jest.fn()},
   },
};

jest.mock('axios', () => {
  return {
    create: () => {
      return mockAxios;
    },
  };
});

And in the test:

mockAxios.get = jest.fn(() => Promise.resolve({ data: {error: 'user or password wrong'} }));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda