1- Basic example showing how to test useReducer hook.
1+ Basic example showing how to test the ` useReducer ` hook.
2+ The most important thing is that we aren't testing the reducer directly - it's an
3+ implementation detail of the component! Instead we are testing the component interface.
24
3- The component we are testing which changes some text depending on ` stateprop1 `
4- value.
5+ The component we are testing changes some text depending on an ` isConfirmed ` state.
56
67``` jsx
8+ // example.js
9+
710import React , { useReducer } from ' react'
811
912const initialState = {
@@ -17,27 +20,14 @@ function reducer(state = initialState, action) {
1720 ... state,
1821 isConfirmed: true ,
1922 }
20- case ' FAILURE' :
21- return {
22- ... state,
23- isConfirmed: true ,
24- }
2523 default :
26- console . log (state )
24+ throw Error ( ' unknown action ' )
2725 }
2826}
2927
3028const Example = () => {
3129 const [state , dispatch ] = useReducer (reducer, initialState)
3230
33- const dispatchActionSuccess = () => {
34- dispatch ({ type: ' SUCCESS' })
35- }
36-
37- const dispatchActionFailure = () => {
38- dispatch ({ type: ' FAILURE' })
39- }
40-
4131 return (
4232 < div>
4333 < div>
@@ -55,19 +45,18 @@ const Example = () => {
5545export default Example
5646```
5747
58- Finally our tests: We are testing to see if we get the correct output in our JSX
48+ We are testing to see if we get the correct output in our JSX
5949based on the reducer state.
6050
61- ``` js
51+ ``` jsx
52+ // example.test.js
53+
6254import React from ' react'
63- import ReactDOM from ' react-dom'
64- import Example from ' ../example.js'
6555import { render , fireEvent , cleanup } from ' @testing-library/react'
56+ import Example from ' ./example.js'
6657
67- afterEach (cleanup)
68-
69- it (' shows success message on click' , () => {
70- const { getByText } = render (< TestHookReducer / > )
58+ it (' shows success message after confirm button is clicked' , () => {
59+ const { getByText } = render (< Example / > )
7160
7261 expect (getByText (/ waiting/ i ).textContent ).toBeInTheDocument ()
7362
0 commit comments