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

176
Views
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
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!