-
Notifications
You must be signed in to change notification settings - Fork 12
/
CommentFormTest.js
66 lines (56 loc) · 2.45 KB
/
CommentFormTest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import CommentForm from "../src/path_to_hooks/HooksCommentForm";
describe("CommentForm", () => {
// This test has both good and bad examples.
//
// Bad practice is to assert presence of exact markup.
//
// Better practice is to assert presence of text and of elements with a
// "role". A "role" here is an implicit ARIA role which generally maps to
// what kind of content a user sees (or hears when vision is impaired!) on the page.
//
// See https://www.w3.org/TR/html-aria/#docconformance for how HTML elements map to roles.
// Do not underestimate the importance of accessibility!
test("has an h3, two text boxes and a button", () => {
const rendering = render(
<CommentForm onSubmit={jest.fn()} text="button-text" />
);
// Bad
expect(rendering.container.innerHTML).toContain(
"<h3>Controlled form</h3>"
);
// Better
screen.getByRole("heading", { name: "Controlled form" });
// Also good
expect(screen.getAllByRole("textbox")).toHaveLength(2);
screen.queryByRole("button", { name: "button-text" });
});
// Testing callbacks and the arguments that callbacks receive is generally
// very useful.
test("calls onSubmit with author and text when submit button clicked", () => {
const onSubmit = jest.fn();
render(<CommentForm onSubmit={onSubmit} text="text" />);
// Using @testing-library query methods and avoiding using .querySelector directly
// forces us towards having an application with good accessibility.
userEvent.type(screen.getByRole("textbox", { name: "Author" }), "foo");
userEvent.type(screen.getByRole("textbox", { name: "Text" }), "bar");
userEvent.click(screen.getByRole("button"));
expect(onSubmit).toHaveBeenCalledWith({ author: "foo", text: "bar" });
});
// Testing any other behaviour that a component has is also useful
test("clears inputs after submit", () => {
render(<CommentForm onSubmit={jest.fn()} text="text" />);
userEvent.type(screen.getByRole("textbox", { name: "Author" }), "foo");
userEvent.type(screen.getByRole("textbox", { name: "Text" }), "bar");
userEvent.click(screen.getByRole("button"));
expect(screen.getByRole("textbox", { name: "Author" })).toHaveProperty(
"value",
""
);
expect(screen.getByRole("textbox", { name: "Text" })).toHaveProperty(
"value",
""
);
});
});