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.