Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!