Skip to content

Instantly share code, notes, and snippets.

@isocroft
Last active May 30, 2025 12:09
Show Gist options
  • Save isocroft/fc1ea5939a2975f040abacdab7d04093 to your computer and use it in GitHub Desktop.
Save isocroft/fc1ea5939a2975f040abacdab7d04093 to your computer and use it in GitHub Desktop.
This is version 1 of a simple test for how using async/await with react testing library can slow down tests
import React, { useState } from "react";
import { render, act, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { roles, Components } from "constants/ui-copy";
function RecipeForm ({ onSubmit }) {
function formToObject(form) {
const formData = new FormData(form);
return Object.fromEntries(formData.entries());
}
return (
<form method="post" onSubmit={(event) => {
event.preventDefault();
onSubmit(formToObject(event.target));
}}>
<h3 role={roles.heading}>Fill Recipe Form</h3>
<input
type="text"
role={roles.textbox}
name={Components.RecipeForm._TextBoxes.title.name}
aria-label={Components.RecipeForm._TextBoxes.title.name}
/>
<input
type="text"
role={roles.textbox}
name={Components.RecipeForm._TextBoxes.description.name}
aria-label={Components.RecipeForm._TextBoxes.description.name}
/>
<input
type="number"
role={roles.spinbutton}
name={Components.RecipeForm._TextBoxes.servings.name}
aria-label={Components.RecipeForm._TextBoxes.servings.name}
/>
<button
role={roles.button}
type="submit"
aria-label={Components.RecipeForm._Buttons.submit.name}
>
Components.RecipeForm._Buttons.submit.text
</button>
</form>
);
}
function setupComponentForUserInteraction(jsx) {
return {
user: userEvent.setup(),
...render(jsx),
};
}
it("should submit correct recipe form data", async () => {
const mockSubmit = jest.fn();
const { user, screen } = setupComponentForUserInteraction(
<RecipeForm onSubmit={mockSubmit} />
);
// Fill the form
await user.type(
screen.getByRole(
roles.textbox,
{ name: Component.RecipeForm._TextBoxes.title.name }
),
"Test recipe",
);
await user.type(
screen.getByRole(
roles.textbox,
{ name: Component.RecipeForm._TextBoxes.description.name }
),
"Delicious recipe",
);
await user.type(
screen.getByRole(
roles.spinbutton,
{ name: Component.RecipeForm._TextBoxes.servings.name }
),
"4"
);
// Save the form
await user.click(
screen.getByRole(
roles.button,
{ name: Components.RecipeForm._Buttons.submit.name }
)
);
expect(mockSubmit).toHaveBeenCalledWith({
name: "Test recipe",
description: "Delicious recipe",
servings: 4,
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment