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

303
Vistas
Jest custom axios interceptor

i am trying to use jest with nextJS to test API. I am using a custom interceptor for all http request to have authorization token on header. Here is my interceptor code

Api.ts

import axios from 'axios';
import config from '../config/index';

const Api = () => {
   const defaultOptions = {
       baseURL: config.APIENDPOINT,
       method: 'get',
       headers: {
           'Content-Type': 'application/json',
       },
   };

   // Create instance
   let instance = axios.create(defaultOptions);

   // Set the AUTH token for any request
   instance.interceptors.request.use((config) => {
       const token = localStorage.getItem('token');
       //@ts-ignore
       config.headers.Authorization = token ? `${token}` : '';
       return config;
   });

   instance.interceptors.response.use((res) => {
       return res
   });

   return instance;
};

export default Api();

Here is the code to call the API

export const loadMerchants = async (id: any) => {    
    const data = await Api.get(config.APIENDPOINT + "/merchants/company/" + id)
    console.log("data" ,data);
    
    return (data)
}

And here is my test code

const axios = require('axios');

jest.mock('axios', () => {
    return {
        get: jest.fn(),
        create: jest.fn(() => ({
            interceptors: {
                request: { use: jest.fn(() => Promise.resolve({ data: { foo: 'bar' } })) },
                response: { use: jest.fn(() => Promise.resolve({ data: { foo: 'bar' } })) },
            }
        }))
    }
})

it('Merchant API call', async () => {
    axios.get.mockResolvedValue({
        data: [
            {
                userId: 1,
                id: 1,
                title: 'My First Album'
            },
            {
                userId: 1,
                id: 2,
                title: 'Album: The Sequel'
            }
        ]
    });

    const merchants = await loadMerchants("1")
    console.log(merchants) //always undefined

    // expect(merchants).toEqual('some data');

});

on my API call if use axios.get instead of Api.get i get the correct results. I have looked into google and haven`t found any solutions.

Any help would be appreciated. Thank you.

about 4 years ago · Juan Pablo Isaza
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