@@ -6,24 +6,27 @@ sidebar_label: Example
6
6
7
7
## Quickstart
8
8
9
- This is a very simple setup to get you started.
9
+ This is a minimal setup to get you started.
10
10
If you want to see a description of what each line does,
11
11
scroll down to the [ annotated version] ( #quickstart-annotated ) .
12
12
Scroll down to [ Full Example] ( #full-example ) to see a more advanced test setup.
13
13
14
14
``` jsx
15
- import {render , fireEvent , waitFor , screen } from ' @testing-library/react'
15
+ import {render , waitFor , screen } from ' @testing-library/react'
16
+ import userEvent from ' @testing-library/user-event'
16
17
import ' @testing-library/jest-dom'
17
18
import Fetch from ' ../fetch'
18
19
20
+ const setup = (jsx )=> ({ user: userEvent .setup (), ... render (jsx) })
21
+
19
22
test (' loads and displays greeting' , async () => {
20
23
21
24
// ARRANGE
22
- render (< Fetch url= " /greeting" / > )
25
+ const { user } = setup (< Fetch url= " /greeting" / > )
23
26
24
27
// ACT
25
- fireEvent .click (screen .getByText (' Load Greeting' ))
26
- await waitFor (() => screen .getByRole (' heading' ) )
28
+ await user .click (screen .getByText (' Load Greeting' ))
29
+ await screen .findByRole (' heading' )
27
30
28
31
// ASSERT
29
32
expect (screen .getByRole (' heading' )).toHaveTextContent (' hello there' )
@@ -37,20 +40,25 @@ test('loads and displays greeting', async () => {
37
40
38
41
``` jsx
39
42
// import react-testing methods
40
- import {render , fireEvent , waitFor , screen } from ' @testing-library/react'
43
+ import {render , waitFor , screen } from ' @testing-library/react'
44
+ import userEvent from ' @testing-library/user-event'
41
45
// add custom jest matchers from jest-dom
42
46
import ' @testing-library/jest-dom'
43
47
// the component to test
44
48
import Fetch from ' ../fetch'
45
49
50
+ // Apply workarounds and mock the UI layer to simulate user interactions
51
+ // like they would happen in the browser
52
+ const setup = (jsx )=> ({ user: userEvent .setup (), ... render (jsx) })
53
+
46
54
test (' loads and displays greeting' , async () => {
47
55
48
- // Render a React element into the DOM
49
- render (< Fetch url= " /greeting" / > )
56
+ // Run the UI setup and render a React element into the DOM
57
+ const { user } = setup (< Fetch url= " /greeting" / > )
50
58
51
- fireEvent .click (screen .getByText (' Load Greeting' ))
52
- // getByRole throws an error if it cannot find an element
53
- await waitFor (() => screen .getByRole (' heading' ) )
59
+ await user .click (screen .getByText (' Load Greeting' ))
60
+ // wait before throwing an error if it cannot find an element
61
+ await screen .findByRole (' heading' )
54
62
55
63
// assert that the alert message is correct using
56
64
// toHaveTextContent, a custom matcher from jest-dom.
0 commit comments