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

179
Visualizações
Jest mock export exposing axios create instance

This is easy but I have been fighting for 5hrs and I don't have a solution yet

app.ts
import { apiClient, getCustomFieldMapping } from './apiClient'

const otherFunction = () => {
   // just to show that getCustomFieldMapping it's used
   getCustomFieldMapping()
}


// route /ext/:userId
const callApi = async (path: string,) => {
     const url = apiClient.defaults.baseURL + path
     return apiClient.get(url);
}
apiClient.ts

import axios from "axios";

export const apiClient = axios.create({
  baseURL: "http://localhost:3000",
  auth: {
    username: `${config.zendeskUsername}/token`,
    password: config.zendeskToken,
  },
});

export const getCustomFieldMapping = (
  from: "fieldId" | "name",
  value: string
): TicketFieldMapping => {
  const fieldMap = fieldMappings.find((mapping) => mapping[from] === value);
  if (!fieldMap) {
    throw {
      message: `Zendesk custom field's mapping from "${from}" "${value}" does not exists.`,
    };
  }
  return fieldMap;
};

What is actually happening is that i'm not been able to only mock the GET api call from the apiClient module.

I have tried a lot of things (listed after this) like:

test.ts

// first try
import axios from 'axios'
jest.mock("axios", () => ({
  create: jest.fn(),
}));
  test("Get user", async () => {
    (axios.create as jest.Mock).mockImplementation(() => {
      return {
        defaults: {
          baseURL: "https://localhost:3000",
        },
        get: jest
          .fn()
          .mockResolvedValueOnce({})
      };
    });
    return request(app)
      .get("/ext/121")
      .expect(StatusCodes.NOT_FOUND)
      .then((response) => {
        console.log(response.body);
      });
  });

// I get that apiClient is undefined

// another one is
const mockGet = jest.fn();
jest.mock("./apiClient", () => {
  const actual = jest.requireActual("./apiClient");
  actual.apiClient.get = jest.fn().mockImplementation(() => mockGet);
  return actual;
});

test("Get user", async () => {
    mockGet.returnResolvedValueOnce({})
    return request(app)
      .get("/ext/121")
      .expect(StatusCodes.NOT_FOUND)
      .then((response) => {
        console.log(response.body);
      });
  });


// here I have two things.. one is that defualts is undefiend and it breaks the run

// otherone it's that getCustomFieldMapping is undefined and can't be called

I want to mock the apiClient GET function. that's it

Thanks in advance

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