Skip to content

Instantly share code, notes, and snippets.

@SatyaAchanta
Created December 25, 2022 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SatyaAchanta/12c7ec835b977ac2bdb107ac9489070d to your computer and use it in GitHub Desktop.
Save SatyaAchanta/12c7ec835b977ac2bdb107ac9489070d to your computer and use it in GitHub Desktop.
test without waitFor on multiple API calls
test("handles error for scoop and toppings", async () => {
server.resetHandlers(
rest.get("http://localhost:3030/scoops", (req, res, ctx) =>
res(ctx.status(500))
),
rest.get("http://localhost:3030/toppings", (req, res, ctx) =>
res(ctx.status(500))
)
);
render(<OrderEntry />);
// in line 14, our intention is to perform `findAllByrole`
// when above both rest calls are completed. However,
// depending on computer speed, we might hit race condition and
// sometimes assertion might happen right after first call, instead of waiting for all calls to finish.
// the fix for this is in the below file, where we wrap below two lines in `await waitFor`
const alerts = await screen.findAllByRole("alert");
expect(alerts).toHaveLength(2);
});
import { render, screen, waitFor } from "@testing-library/react";
import OrderEntry from "../OrderEntry";
import { rest } from "msw";
import { server } from "../../../mocks/server";
test("handles error for scoop and toppings", async () => {
server.resetHandlers(
rest.get("http://localhost:3030/scoops", (req, res, ctx) =>
res(ctx.status(500))
),
rest.get("http://localhost:3030/toppings", (req, res, ctx) =>
res(ctx.status(500))
)
);
render(<OrderEntry />);
/**
* If we are asseting multiple things , then use waitFor
* to not assert before all the calls happened
*
* without waitfor, our assert statement gets executed after first call
* even though we have few more calls to be resolved.
*/
await waitFor(async () => {
const alerts = await screen.findAllByRole("alert");
expect(alerts).toHaveLength(2);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment