Created
December 25, 2022 18:35
-
-
Save SatyaAchanta/12c7ec835b977ac2bdb107ac9489070d to your computer and use it in GitHub Desktop.
test without waitFor on multiple API calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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