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

172
Vistas
Jest mock function that is exported an used at the same module

hihi

I have a module that exports two functions

// foo.js
export const apiClient = axios.create({ 
    baseURL: "www.randomapi.com",
});

export const search = async (q: string) => {
    return apiClient.get("/search.json", {params: { q });
}

And then anotherone that imports search

// bar.js

import { search } from "foo"

export const searchByQuery = async (q: string) => {
// some process with the Q
return (await search(q)).data

}

So what I need to do it somehow mock that apiClient.get in the search use

//test.js
import { searchByQuery } from "bar"
jest.mock("./foo.js", () => ({
  ...jest.requireActual("./foo.js"),
  ApiClient: {
    get: async () => ({
      data: {
        results: [
          {
            "name": "John",
            "age": 20
          },
        ],
      },
    }),
  },
}));

test('It should mock', async () => {
    const result = await searchByQuery("John");
    expect(result[0].name).toBe("John");
})

The result is that the apiClient it's not being mocked and it's doing the real api call to the URL.

Another way to do it would be mocking the search function. That's something I already did and it was successful but it's not what I'm looking for because I want to test the errors from the randomapi.com

I did another test using the same mock where apiClient.get is called from bar.js and it's working.

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