Reputation: 11
I am writing mocks responses (using MSW) for a test case for an API call when a page is rendered in vitest and I am unable to trigger the REST API call defined in a handler.
Technically, if the API is called a print out is supposed to appear and my data should load, but neither are happening which is what seems to be the problem
handler.js
import { http } from "msw";
export const handler = [
http.get("*/api/job/print/", (req, res, ctx) => {
// const page = req.url.searchParams.get("page");
const in_progress = req.url.searchParams.get("in_progress");
// const expand = req.url.searchParams.get("expand");
console.log("IM CALLED");
// console.log(req.url);
if (in_progress === "true") {
return res(
ctx.status(200),
ctx.json({
count: 1,
next: null,
previous: null,
results: [/*some data*/]
)
}
]
testcase.test.jsx
import { render, screen, waitFor } from "@testing-library/react";
import { beforeAll, describe, it } from "vitest";
import { MemoryRouter } from "react-router-dom";
import PrintingPage from "../../../../pages/JobPage";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { server } from "./mocks/APIServer";
describe("Jobs hook", () => {
const client = new QueryClient();
beforeAll(() => {
server.events.on("request:start", ({ request }) => {
console.log("Request intercepted:", request.method, request.url);
});
});
it("should return a list of print Jobs", async () => {
//rendering PrintingPage will call "/api/job/print/" rest API
render(
<QueryClientProvider client={client}>
<MemoryRouter>
<PrintingPage />
</MemoryRouter>
</QueryClientProvider>
);
await waitFor(() => {
screen.debug();
// expect(screen.getByText("Retrieving data...")).not.toBeInTheDocument();
});
});
});
I tried to debug by listening and printing out the intercepted calls.
the output shows that the API calls are being intercepted
Request intercepted: GET http://x.x.x.x:XXXX/api/job/print/?in_progress=false Request intercepted: GET http://x.x.x.x:XXXX/api/job/print/?in_progress=true
.
However I do not get the printout to notify me that the handler API is called as shown in the code above I should be seeing a "IM CALLED" printed out in the log.
I've also checked that the frontend's (this proj) API point is being called to ensure that there is a request being made to the server.
Below is the server code that has been defined as well:
APIServer.js
import { setupServer } from "msw/node";
import { handler as JobsHandler } from "./JobsHandler";
export const server = setupServer(...JobsHandler);
The test setup is the following (based on MSW's integration documentation).
vitest.setup.js
import "@testing-library/jest-dom";
import { server } from "./src/features/job/hooks/__tests__/mocks/APIServer";
import { beforeAll, afterEach, afterAll } from "vitest";
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Upvotes: 1
Views: 31