-
Every example I see for Axios mocking is using the non static Axios instance... e.g. // activities.service.ts
async function getActivities() {
// I want to be able to mock this response
const { data } = await axios({
method: "post",
url: "www.some-url.com",
params: {
access_token: myAccessToken
}
});
// data gets processed, and then I eventually return something, but it's not important what it is
return processedData;
} The resulting e2e test would look something like this: vi.mock("axios");
// TODO: I get a type error here saying it can't convert AxiosStatic to MockedFunction<AxiosStatic> and that I should use unknown, so what should this be?
const mockedAxios = axios as MockedFunction<AxiosStatic>;
describe("e2e", async () => {
it("Should complete the request", async () => {
// TODO: This says params is a string, but it's not, it's the options that are passed in
mockedAxios.mockImplementation((params) => {
console.log("HERE", params);
return Promise.resolve({
data: {},
});
});
// This will hit the activities.controller, which will call the activities.service.getActivities method
const response = await request(app.getHttpServer()).get("/activities");
});
}); So, while the above does work, there are type issues, and I'd like to resolve them properly. I think the main issue is the mockedAxios const being incorrect, but I don't know how to type it. Does anyone have any idea? Also, if I'm doing something else wrong, I'm all ears, but like I said, I can't mock the Axios methods individually... like I can't do the following: mockedAxios.post.mockImplementation((url, params) => {
console.log("this will not get hit", params);
return Promise.resolve({
data: {},
});
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
What I ended up doing was changing my vi.mock("axios");
const mockedAxios = vi.mocked(axios, true);
// further down in the test
mockedAxios.request.mockImplementation(({ url }) => {
switch(url) {
case "www.some-url.com":
return Promise.resolve({ data: [] });
default:
return Promise.resolve({ data: {} });
}
}); Not sure if simply calling |
Beta Was this translation helpful? Give feedback.
What I ended up doing was changing my
axios({
calls toaxios.request({
, and then I was able to mock like this:Not sure if simply calling
axios({
is a bad practice, but being able to sub in request and get my desired outcome has fixed my issues.