@@ -35,17 +35,6 @@ practices.</p>
3535- [ The Problem] ( #the-problem )
3636- [ The Solution] ( #the-solution )
3737- [ Installation] ( #installation )
38- - [ Usage] ( #usage )
39- - [ ` render ` ] ( #render )
40- - [ ` cleanup ` ] ( #cleanup )
41- - [ ` act ` ] ( #act )
42- - [ ` fireEvent ` ] ( #fireevent )
43- - [ ` @testing-library/dom ` ] ( #testing-librarydom )
44- - [ Example] ( #example )
45- - [ Component] ( #component )
46- - [ Test] ( #test )
47- - [ Hooks] ( #hooks )
48- - [ Guiding Principles] ( #guiding-principles )
4938- [ Docs] ( #docs )
5039- [ Issues] ( #issues )
5140 - [ 🐛 Bugs] ( #-bugs )
@@ -58,11 +47,8 @@ practices.</p>
5847
5948## The Problem
6049
61- You want to write maintainable tests for your Preact components. As a part of this goal, you want
62- your tests to avoid including implementation details of your components and rather focus on making
63- your tests give you the confidence for which they are intended. As part of this, you want your
64- testbase to be maintainable in the long run so refactors of your components (changes to
65- implementation but not functionality) don't break your tests and slow you and your team down.
50+ You want to write tests for your Preact components so that they avoid including implementation
51+ details, and are maintainable in the long run.
6652
6753## The Solution
6854
@@ -91,228 +77,10 @@ This library has `peerDependencies` listings for `preact >= 10`.
9177
9278📝 If you're looking for a solution for Preact 8.x then install ` preact-testing-library ` .
9379
94- ## Usage
95-
96- ### ` render `
97-
98- ``` jsx
99- import { render } from ' @testing-library/preact'
100-
101- const { returns } = render (< YourComponent / > , { arguments })
102- ```
103-
104- | Arguments | Description | Default |
105- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
106- | ` container ` | The HTML element the component is mounted to. | baseElement |
107- | ` baseElement ` | The root HTML element to which the container is appended to. | document.body |
108- | ` queries ` | Queries to bind to the baseElement. See [ getQueriesForElement] ( https://testing-library.com/docs/dom-testing-library/api-helpers#within-and-getqueriesforelement-apis ) . | null |
109- | ` 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 |
110- | ` wrapper ` | A parent component to wrap YourComponent. | null |
111-
112- | Returns | Description |
113- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
114- | ` container ` | The HTML element the component is mounted to. |
115- | ` baseElement ` | The root HTML element to which the container is appended to. |
116- | ` debug ` | Logs the baseElement using [ prettyDom] ( https://testing-library.com/docs/dom-testing-library/api-helpers#prettydom ) . |
117- | ` unmount ` | Unmounts the component from the container. |
118- | ` rerender ` | Calls render again passing in the original arguments and sets hydrate to true. |
119- | ` asFragment ` | Returns the innerHTML of the container. |
120- | ` ...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. |
121-
122- ### ` cleanup `
123-
124- Unmounts the component from the container and destroys the container.
125-
126- 📝 When you import anything from the library, this automatically runs after each test. If you'd like
127- to disable this then set ` process.env.PTL_SKIP_AUTO_CLEANUP ` to true when running your tests.
128-
129- ``` jsx
130- import { render , cleanup } from ' @testing-library/preact'
131-
132- afterEach (() => {
133- cleanup
134- }) // Default on import: runs it after each test.
135-
136- render (< YourComponent / > )
137-
138- cleanup () // Or like this for more control.
139- ```
140-
141- ### ` act `
142-
143- Just a convenience export that points to preact/test-utils/act. All renders and events being fired
144- are wrapped in ` act ` , so you don't really need this. It's responsible for flushing all effects and
145- rerenders after invoking it.
146-
147- 📝 If you'd love to learn more, checkout
148- [ this explanation] ( https://github.com/threepointone/react-act-examples/blob/master/sync.md ) . Even
149- thought it's for React, it gives you an idea of why it's needed.
150-
151- ### ` fireEvent `
152-
153- Passes it to the @testing-library/dom
154- [ fireEvent] ( https://testing-library.com/docs/dom-testing-library/api-events ) . It's also wrapped in
155- ` act ` so you don't need to worry about doing it.
156-
157- 📝 Keep in mind mainly when using ` h / Preact.createElement ` that React uses a Synthetic event
158- system, and Preact uses the browser's native ` addEventListener ` for event handling. This means
159- events like ` onChange ` and ` onDoubleClick ` in React, are ` onInput ` and ` onDblClick ` in Preact. The
160- double click example will give you an idea of how to test using those functions.
161-
162- ``` jsx
163- const cb = jest .fn ();
164-
165- function Counter () {
166- useEffect (cb);
167-
168- const [count , setCount ] = useState (0 );
169-
170- return < button onClick= {() => setCount (count + 1 )}> {count}< / button> ;
171- }
172-
173- const { container: { firstChild: buttonNode }, } = render (< Counter / > );
174-
175- // Clear the first call to useEffect that the initial render triggers.
176- cb .mockClear ();
177-
178- // Fire event Option 1.
179- fireEvent .click (buttonNode);
180-
181- // Fire event Option 2.
182- fireEvent (
183- button,
184- new Event (' MouseEvent' , {
185- bubbles: true ,
186- cancelable: true ,
187- button: 0 ,
188- });
189-
190- expect (buttonNode).toHaveTextContent (' 1' );
191- expect (cb).toHaveBeenCalledTimes (1 );
192- ` ` `
193-
194- ` ` ` jsx
195- const handler = jest .fn ()
196-
197- const {
198- container: { firstChild: input },
199- } = render (< input type= " text" onInput= {handler} / > )
200-
201- fireEvent .input (input, { target: { value: ' a' } })
202-
203- expect (handler).toHaveBeenCalledTimes (1 )
204- ` ` `
205-
206- ` ` ` jsx
207- const ref = createRef ()
208- const spy = jest .fn ()
209-
210- render (
211- h (elementType, {
212- onDblClick: spy,
213- ref,
214- }),
215- )
216-
217- fireEvent[' onDblClick' ](ref .current )
218-
219- expect (spy).toHaveBeenCalledTimes (1 )
220- ` ` `
221-
222- ### ` @testing- library/ dom`
223-
224- This library re-exports everything from ` @testing- library/ dom` . See the
225- [documentation](https://testing-library.com/docs/dom-testing-library/intro) to see what goodies you
226- can use. The helper functions like ` wait` can be particularly useful.
227-
228- ## Example
229-
230- #### Component
231-
232- _Note: Preact Testing Library works with both Preact Hooks and Classes. Your tests will be the same
233- however you write your components._
234-
235- ` ` ` jsx
236- function HiddenMessage ({ children }) {
237- const [showMessage , setShowMessage ] = useState (false )
238-
239- return (
240- < div>
241- < label htmlFor= " toggle" > Show Message< / label>
242- < input
243- id= " toggle"
244- type= " checkbox"
245- onChange= {e => setShowMessage (e .target .checked )}
246- checked= {showMessage}
247- / >
248- {showMessage ? children : null }
249- < / div>
250- )
251- }
252- ` ` `
253-
254- #### Test
255-
256- ` ` ` jsx
257- // NOTE: jest-dom adds handy assertions to Jest and it is recommended, but not required.
258- import ' @testing-library/jest-dom/extend-expect'
259-
260- import { h } from ' preact'
261- import { render , fireEvent } from ' @testing-library/preact'
262- import HiddenMessage from ' ../hidden-message'
263-
264- test (' shows the children when the checkbox is checked' , () => {
265- const testMessage = ' Test Message'
266-
267- const { queryByText , getByLabelText , getByText } = render (
268- < HiddenMessage> {testMessage}< / HiddenMessage> ,
269- )
270-
271- // query* functions will return the element or null if it cannot be found.
272- // get* functions will return the element or throw an error if it cannot be found.
273- expect (queryByText (testMessage)).toBeNull ()
274-
275- // The queries can accept a regex to make your selectors more resilient to content tweaks and changes.
276- fireEvent .click (getByLabelText (/ show/ i ))
277-
278- // .toBeInTheDocument() is an assertion that comes from jest-dom.
279- // Otherwise you could use .toBeDefined().
280- expect (getByText (testMessage)).toBeInTheDocument ()
281- })
282- ` ` `
283-
284- ## Hooks
285-
286- If you are interested in testing a custom hook, the preact-hooks-testing-library will be coming
287- soon.
288-
289- > It is not recommended to test single-use custom hooks in isolation from the components where it's
290- > being used. It's better to test the component that's using the hook rather than the hook itself.
291- > The preact-hooks-testing-library will be intended to be used for reusable hooks/libraries.
292-
293- ## Guiding Principles
294-
295- We try to only expose methods and utilities that encourage you to write tests that closely resemble
296- how your Preact components are used.
297-
298- Utilities are included in this project based on the following
299- [guiding principles](https://twitter.com/kentcdodds/status/977018512689455106).
300-
30180## Docs
30281
303- For more information checkout:
304-
305- - The react-testing-library [documentation][react-testing-library-docs].
306- - The react-testing-library
307- [sandbox](https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples).
308- - Extend Jest with [custom matchers](https://github.com/testing-library/jest-dom) to test the state
309- of the DOM.
310- - The testing library [documentation](https://testing-library.com/docs/intro).
311- - [Queries](https://testing-library.com/docs/dom-testing-library/api-queries).
312- - [Events](https://testing-library.com/docs/dom-testing-library/api-events).
313-
314- Even though they are all React based examples, it should be close to identical in Preact. Take note
315- of the [differences between React and Preact](https://preactjs.com/guide/v10/differences-to-react).
82+ See the [ docs] ( https://testing-library.com/docs/preact-testing-library/intro ) over at the Testing
83+ Library website.
31684
31785## Issues
31886
0 commit comments