Skip to content

Commit b20b50a

Browse files
authored
Add quickstart example
1 parent d61fd25 commit b20b50a

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

docs/react-testing-library/example-intro.mdx

+59
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,65 @@ title: Example
44
sidebar_label: Example
55
---
66

7+
## Quickstart
8+
9+
This is a very simple setup to get you started.
10+
If you want to see a description of what each line does,
11+
scroll down to the [annotated version](#quickstart-annotated).
12+
Scroll down to [Full Example](#full-example) to see a more advanced test setup.
13+
14+
```jsx
15+
import {render, fireEvent, waitFor, screen} from '@testing-library/react'
16+
import '@testing-library/jest-dom'
17+
import Fetch from '../fetch'
18+
19+
test('loads and displays greeting', async () => {
20+
21+
// ARRANGE
22+
render(<Fetch url="/greeting" />)
23+
24+
// ACT
25+
fireEvent.click(screen.getByText('Load Greeting'))
26+
await waitFor(() => screen.getByRole('heading'))
27+
28+
// ASSERT
29+
expect(screen.getByRole('heading')).toHaveTextContent('hello there')
30+
expect(screen.getByRole('button')).toBeDisabled()
31+
32+
})
33+
```
34+
35+
<details id="quickstart-annotated">
36+
<summary>Quickstart (Annotated Example)</summary>
37+
38+
```jsx
39+
// import react-testing methods
40+
import {render, fireEvent, waitFor, screen} from '@testing-library/react'
41+
// add custom jest matchers from jest-dom
42+
import '@testing-library/jest-dom'
43+
// the component to test
44+
import Fetch from '../fetch'
45+
46+
test('loads and displays greeting', async () => {
47+
48+
// Render a React element into the DOM
49+
render(<Fetch url="/greeting" />)
50+
51+
fireEvent.click(screen.getByText('Load Greeting'))
52+
// getByRole throws an error if it cannot find an element
53+
await waitFor(() => screen.getByRole('heading'))
54+
55+
// assert that the alert message is correct using
56+
// toHaveTextContent, a custom matcher from jest-dom.
57+
expect(screen.getByRole('heading')).toHaveTextContent('hello there')
58+
expect(screen.getByRole('button')).toBeDisabled()
59+
60+
})
61+
```
62+
63+
</details>
64+
65+
766
## Full Example
867

968
See the following sections for a detailed breakdown of the test

0 commit comments

Comments
 (0)