File tree Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Original file line number Diff line number Diff line change 1+ Basic example showing how to test useReducer hook.
2+
3+
4+ The component we are testing which changes some text depending on ` stateprop1 ` value.
5+
6+ ``` jsx
7+ import React , { useReducer } from ' react'
8+
9+ const initialState = {
10+ isConfirmed: false ,
11+ }
12+
13+ function reducer (state = initialState , action ) {
14+ switch (action .type ) {
15+ case " SUCCESS" :
16+ return {
17+ ... state,
18+ isConfirmed: true ,
19+ }
20+ case " FAILURE" :
21+ return {
22+ ... state,
23+ isConfirmed: true ,
24+ }
25+ default :
26+ console .log (state)
27+ }
28+ }
29+
30+ const Example = () => {
31+ const [state , dispatch ] = useReducer (reducer, initialState)
32+
33+ const dispatchActionSuccess = () => {
34+ dispatch ({ type: ' SUCCESS' })
35+ }
36+
37+ const dispatchActionFailure = () => {
38+ dispatch ({ type: ' FAILURE' })
39+ }
40+
41+ return (
42+ < div>
43+ < div>
44+ {state .isConfirmed
45+ ? < p> Confirmed! < / p>
46+ : < p> Waiting for confirmation... < / p> }
47+ < / div>
48+ < button onClick= {dispatch ({type: ' SUCCESS' })}>
49+ Confirm
50+ < / button>
51+ < / div>
52+ )
53+ }
54+
55+ export default Example
56+ ```
57+
58+
59+ Finally our tests: We are testing to see if we get the correct output in our JSX based on the reducer state.
60+
61+ ``` js
62+ import React from ' react'
63+ import ReactDOM from ' react-dom'
64+ import Example from ' ../example.js'
65+ import {render , fireEvent , cleanup } from ' @testing-library/react'
66+
67+ afterEach (cleanup)
68+
69+ it (' shows success message on click' , () => {
70+ const { getByText } = render (< TestHookReducer / > )
71+
72+ expect (getByText (/ waiting/ i ).textContent ).toBeInTheDocument ()
73+
74+ fireEvent .click (getByText (" Confirm" ))
75+
76+ expect (getByText (' Confirmed' )).toBeInTheDocument ()
77+ })
78+ ```
You can’t perform that action at this time.
0 commit comments