Skip to content

Commit 8f7d5d0

Browse files
mihar-22Kent C. Dodds
authored andcommitted
docs(preact): release initial docs (testing-library#273)
* docs(preact): add logo + link to homepage * docs(preact): release initial docs
1 parent 8100f03 commit 8f7d5d0

File tree

7 files changed

+312
-0
lines changed

7 files changed

+312
-0
lines changed

docs/preact-testing-library/api.md

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
---
2+
id: api
3+
title: API
4+
sidebar_label: API
5+
---
6+
7+
- [`@testing-library/dom`](#testing-library-dom)
8+
- [`render`](#render)
9+
- [`cleanup`](#cleanup)
10+
- [`act`](#act)
11+
- [`fireEvent`](#fireevent)
12+
13+
---
14+
15+
## `@testing-library/dom`
16+
17+
This library re-exports everything from the DOM Testing Library
18+
(`@testing-library/dom`). See the
19+
[documentation](../dom-testing-library/api-queries.md) to see what goodies you
20+
can use.
21+
22+
## `render`
23+
24+
```jsx
25+
import { render } from '@testing-library/preact'
26+
27+
const { results } = render(<YourComponent />, { options })
28+
```
29+
30+
### Options
31+
32+
| Option | Description | Default |
33+
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
34+
| `container` | The HTML element the component is mounted to. | baseElement |
35+
| `baseElement` | The root HTML element to which the container is appended to. | document.body |
36+
| `queries` | Queries to bind to the baseElement. See [getQueriesForElement](../dom-testing-library/api-helpers#within-and-getqueriesforelement-apis). | null |
37+
| `hydrate` | Used when the component has already been mounted and requires a rerender. Not needed for most people. The rerender function passed back to you does this already. | false |
38+
| `wrapper` | A parent component to wrap YourComponent. | null |
39+
40+
### Results
41+
42+
| Result | Description |
43+
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
44+
| `container` | The HTML element the component is mounted to. |
45+
| `baseElement` | The root HTML element to which the container is appended to. |
46+
| `debug` | Logs the baseElement using [prettyDom](https://testing-library.com/docs/dom-testing-library/api-helpers#prettydom). |
47+
| `unmount` | Unmounts the component from the container. |
48+
| `rerender` | Calls render again passing in the original arguments and sets hydrate to true. |
49+
| `asFragment` | Returns the innerHTML of the container. |
50+
| `...queries` | Returns all [query functions](https://testing-library.com/docs/dom-testing-library/api-queries) to be used on the baseElement. If you pass in `query` arguments than this will be those, otherwise all. |
51+
52+
## `cleanup`
53+
54+
Unmounts the component from the container and destroys the container.
55+
56+
📝 When you import anything from the library, this automatically runs after each
57+
test. If you'd like to disable this then set `process.env.PTL_SKIP_AUTO_CLEANUP`
58+
to true when running your tests.
59+
60+
```jsx
61+
import { render, cleanup } from '@testing-library/preact'
62+
63+
afterEach(() => {
64+
cleanup()
65+
}) // Default on import: runs it after each test.
66+
67+
render(<YourComponent />)
68+
69+
cleanup() // Or like this for more control.
70+
```
71+
72+
## `act`
73+
74+
Just a convenience export that points to preact/test-utils/act. All renders and
75+
events being fired are wrapped in `act`, so you don't really need this. It's
76+
responsible for flushing all effects and rerenders after invoking it.
77+
78+
📝 If you'd love to learn more, checkout
79+
[this explanation](https://github.com/threepointone/react-act-examples/blob/master/sync.md).
80+
Even thought it's for React, it gives you an idea of why it's needed.
81+
82+
## `fireEvent`
83+
84+
Passes it to the @testing-library/dom
85+
[fireEvent](../dom-testing-library/api-events). It's also wrapped in `act` so
86+
you don't need to worry about doing it.
87+
88+
📝 Keep in mind mainly when using `h / Preact.createElement` that React uses a
89+
Synthetic event system, and Preact uses the browser's native `addEventListener`
90+
for event handling. This means events like `onChange` and `onDoubleClick` in
91+
React, are `onInput` and `onDblClick` in Preact. The double click example will
92+
give you an idea of how to test using those functions.
93+
94+
### Example 1
95+
96+
```jsx
97+
const cb = jest.fn();
98+
99+
function Counter() {
100+
useEffect(cb);
101+
102+
const [count, setCount] = useState(0);
103+
104+
return <button onClick={() => setCount(count + 1)}>{count}</button>;
105+
}
106+
107+
const { container: { firstChild: buttonNode }, } = render(<Counter />);
108+
109+
// Clear the first call to useEffect that the initial render triggers.
110+
cb.mockClear();
111+
112+
// Fire event Option 1.
113+
fireEvent.click(buttonNode);
114+
115+
// Fire event Option 2.
116+
fireEvent(
117+
button,
118+
new Event('MouseEvent', {
119+
bubbles: true,
120+
cancelable: true,
121+
button: 0,
122+
});
123+
124+
expect(buttonNode).toHaveTextContent('1');
125+
expect(cb).toHaveBeenCalledTimes(1);
126+
```
127+
128+
### Example 2
129+
130+
```jsx
131+
const handler = jest.fn()
132+
133+
const {
134+
container: { firstChild: input },
135+
} = render(<input type="text" onInput={handler} />)
136+
137+
fireEvent.input(input, { target: { value: 'a' } })
138+
139+
expect(handler).toHaveBeenCalledTimes(1)
140+
```
141+
142+
### Example 3
143+
144+
```jsx
145+
const ref = createRef()
146+
const spy = jest.fn()
147+
148+
render(
149+
h(elementType, {
150+
onDblClick: spy,
151+
ref,
152+
})
153+
)
154+
155+
fireEvent['onDblClick'](ref.current)
156+
157+
expect(spy).toHaveBeenCalledTimes(1)
158+
```
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
id: example
3+
title: Example
4+
sidebar_label: Example
5+
---
6+
7+
> Preact Testing Library works with both Preact Hooks and Classes. Your tests
8+
> will be the same however you write your components.
9+
10+
## Component
11+
12+
```jsx
13+
function HiddenMessage({ children }) {
14+
const [showMessage, setShowMessage] = useState(false)
15+
16+
return (
17+
<div>
18+
<label htmlFor="toggle">Show Message</label>
19+
<input
20+
id="toggle"
21+
type="checkbox"
22+
onChange={e => setShowMessage(e.target.checked)}
23+
checked={showMessage}
24+
/>
25+
{showMessage ? children : null}
26+
</div>
27+
)
28+
}
29+
```
30+
31+
## Test
32+
33+
```jsx
34+
// NOTE: jest-dom adds handy assertions to Jest and it is recommended, but not required.
35+
import '@testing-library/jest-dom/extend-expect'
36+
37+
import { h } from 'preact'
38+
import { render, fireEvent } from '@testing-library/preact'
39+
40+
import HiddenMessage from '../hidden-message'
41+
42+
test('shows the children when the checkbox is checked', () => {
43+
const testMessage = 'Test Message'
44+
45+
const { queryByText, getByLabelText, getByText } = render(
46+
<HiddenMessage>{testMessage}</HiddenMessage>
47+
)
48+
49+
// query* functions will return the element or null if it cannot be found.
50+
// get* functions will return the element or throw an error if it cannot be found.
51+
expect(queryByText(testMessage)).toBeNull()
52+
53+
// The queries can accept a regex to make your selectors more resilient to content tweaks and changes.
54+
fireEvent.click(getByLabelText(/show/i))
55+
56+
// .toBeInTheDocument() is an assertion that comes from jest-dom.
57+
// Otherwise you could use .toBeDefined().
58+
expect(getByText(testMessage)).toBeInTheDocument()
59+
})
60+
```
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
---
2+
id: intro
3+
title: Intro
4+
sidebar_label: Introduction
5+
---
6+
7+
[Preact Testing Library on GitHub][gh]
8+
9+
[gh]: https://github.com/testing-library/preact-testing-library
10+
11+
```
12+
npm install --save-dev @testing-library/preact
13+
```
14+
15+
> This library is built on top of
16+
> [`DOM Testing Library`](dom-testing-library/intro.md) which is where most of
17+
> the logic behind the queries is.
18+
19+
## The Problem
20+
21+
You want to write tests for your Preact components so that they avoid including
22+
implementation details, and are maintainable in the long run.
23+
24+
## This Solution
25+
26+
The Preact Testing Library is a very lightweight solution for testing Preact
27+
components. It provides light utility functions on top of `preact/test-utils`,
28+
in a way that encourages better testing practices. Its primary guiding principle
29+
is:
30+
31+
> [The more your tests resemble the way your software is used, the more confidence they can give you.](https://twitter.com/kentcdodds/status/977018512689455106)
32+
33+
See the [Dom introduction][dom-solution-explainer] and [React
34+
introduction][react-solution-explainer] for a more in-depth explanation.
35+
36+
[dom-solution-explainer]: ../dom-testing-library/intro.md#this-solution
37+
[react-solution-explainer]: ../react-testing-library/intro#this-solution
38+
39+
**What this library is not**:
40+
41+
1. A test runner or framework.
42+
2. Specific to a testing framework.
43+
44+
We recommend Jest as our preference. You can checkout
45+
[Using Without Jest](../react-testing-library/setup#using-without-jest) if
46+
you're looking to use another framework.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
id: learn
3+
title: Learn
4+
sidebar_label: Learn
5+
---
6+
7+
Due to the similarities between React and Preact (including the testing
8+
libraries), you should be able to comfortably use any React based examples,
9+
docs, answers on stack overflow etc.
10+
11+
Take note of the
12+
[differences between React and Preact](https://preactjs.com/guide/v10/differences-to-react).
13+
14+
If you're still hungry for more at this point than checkout:
15+
16+
- The dom-testing-library:
17+
- [Introduction](../intro.md)
18+
- [Queries](../dom-testing-library/api-queries)
19+
- [Firing Events](../dom-testing-library/api-events)
20+
- [Async Utilities](../dom-testing-library/api-async.md)
21+
- [Helpers](../dom-testing-library/api-helpers)
22+
- [FAQ](../dom-testing-library/faq.md)
23+
- The react-testing-library:
24+
- [API](../react-testing-library/api.md)
25+
- [Example](../react-testing-library/example-intro.md)
26+
- [Sandbox](https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples)
27+
- [FAQ](../react-testing-library/faq.md)
28+
- This YouTube video by LevelUpTuts called
29+
[What is React Testing Library?](https://youtu.be/JKOwJUM4_RM)
30+
- Extending Jest with
31+
[custom matchers](https://github.com/testing-library/jest-dom) to test the
32+
state of the DOM.

website/pages/en/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,12 @@ class Index extends React.Component {
235235
title:
236236
'[Native Testing Library](./docs/native-testing-library/intro)',
237237
},
238+
{
239+
image: `${baseUrl}img/preact-128x128.png`,
240+
imageAlign: 'top',
241+
title:
242+
'[Preact Testing Library](./docs/preact-testing-library/intro)',
243+
},
238244
{
239245
image: `${baseUrl}img/construction-128x128.png`,
240246
imageAlign: 'top',

website/sidebars.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,16 @@
8080
"angular-testing-library/api"
8181
]
8282
},
83+
{
84+
"type": "subcategory",
85+
"label": "Preact Testing Library",
86+
"ids": [
87+
"preact-testing-library/intro",
88+
"preact-testing-library/example",
89+
"preact-testing-library/api",
90+
"preact-testing-library/learn"
91+
]
92+
},
8393
"cypress-testing-library/intro",
8494
"svelte-testing-library/intro",
8595
"pptr-testing-library/intro",
11 KB
Loading

0 commit comments

Comments
 (0)