I'm trying to create a mock for a custom hook that makes use of useEffect and use/createContext and ultimately just returns something that looks like this:
[{ users: 0, hoursTested: 0, testDrives: 0 }, null];
My code is as follow:
import React from "react";
import { render, screen } from "@testing-library/react";
import BetaResults from "./BetaResults";
var mockResults = [{ users: 0, hoursTested: 0, testDrives: 0 }, null];
jest.mock("services/EAPStats/useEAPStats", () => {
console.log("In Mock");
return jest.fn(() => {
console.log("In jest.fn");
console.log("mock results", mockResults);
return mockResults;
});
});
test("renders BetaResults", async () => {
mockResults = [{ users: 10, hoursTested: 10, testDrives: 10 }, undefined];
render(<BetaResults />);
expect(screen.getAllByTestId("BetaResultsHeaderText").length).toEqual(1);
});
When I execute the test I receive this error:
Error: Uncaught [TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))]
Execution never reaches the function defined with jest.fn. What have I overlooked?
So I ended up going a different route with this and thought I'd post what I did for anyone else that struggles with implementing tests around React hooks and fetch calls. Rather than doing all of the mocking stuff, I just went with msw and it's much cleaner. Below is the code:
import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import BetaResults from "./BetaResults";
import { rest } from "msw";
import { setupServer } from "msw/node";
const server = setupServer(
rest.get("/api/EAPStats.json", (req, res, ctx) => {
return res(ctx.json({ users: 10, hoursTested: 1000, testDrives: 100 }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test("renders BetaResults", async () => {
render(<BetaResults />);
// Wait for the hook to fire and retrieve data. Initial render is loading component.
await waitFor(() => screen.getByTestId("resultsBackground"));
expect(screen.getByTestId("hoursTested").innerHTML).toEqual("1000");
expect(screen.getByTestId("users").innerHTML).toEqual("10");
expect(screen.getByTestId("testDrives").innerHTML).toEqual("100");
});
Pretty straightforward and easy to see how to expand on this.