File tree 4 files changed +55
-4
lines changed
4 files changed +55
-4
lines changed Original file line number Diff line number Diff line change @@ -64,10 +64,18 @@ Simplify tests with react-testing-library:
64
64
- replace modification of input value
65
65
66
66
67
- ## 05 react-redux
67
+ ## 05 mock API data and timers
68
68
> [ src/05] ( src/05 )
69
69
70
- - existing actions, reducer, ... and simple tests for them
71
- - add useDispatch, useSelector to component
72
- - mock the selectors, use dummy dispatch and connect
70
+ Use standard Jest mocking features:
71
+ - mock response from window.fetch
72
+ - mock setTimeout
73
73
74
+
75
+ ## 06 react-redux
76
+ > [ src2/06] ( src2/06 )
77
+
78
+ [ You Might Not Need Redux] ( https://www.google.com/search?q=you+might+not+need+redux ) , but if it's already used in the project
79
+ and you want to test a component:
80
+ - mock ` useSelector ` , ` useDispacth ` and ` connect `
81
+ - or [ redux-mock-store] ( https://github.com/dmitry-zaets/redux-mock-store ) (out of scope for today)
Original file line number Diff line number Diff line change
1
+ import React , { useEffect } from 'react'
2
+ // import { useDispatch, useSelector } from 'react-redux'
3
+ import { useDispatch , useSelector } from './react-redux'
4
+
5
+ const fetchData = ( dispatch ) => window . fetch ( '/api/data' ) . then ( ( { data } ) => dispatch ( { type : 'DATA_SUCCESS' , data } ) )
6
+ const dataSelector = ( state ) => state . api13 . data
7
+
8
+ const Main = ( ) => {
9
+ const { data } = useSelector ( dataSelector )
10
+ const dispatch = useDispatch ( )
11
+ useEffect ( ( ) => {
12
+ dispatch ( fetchData )
13
+ } , [ dispatch ] )
14
+
15
+ return ! data ? ( 'Loading...' ) : (
16
+ < ul > { data . map ( ( { id } ) => < li key = { id } > { id } </ li > ) } </ ul >
17
+ )
18
+ }
19
+
20
+ export default Main
Original file line number Diff line number Diff line change
1
+ import React from 'react'
2
+ import { render } from '@testing-library/react'
3
+ import Main from './06-solution'
4
+
5
+ // jest.mock('react-redux', () => ({
6
+ jest . mock ( './react-redux' , ( ) => ( {
7
+ useDispatch : ( ) => jest . fn ( ) ,
8
+ useSelector : ( ) => ( { data : [ { id : 2 } ] } ) ,
9
+ // useSelector: (selectorFn) => {
10
+ // switch (selectorFn.name) {
11
+ // case 'dataSelector':
12
+ // return { data: [{ id: 2 }] }
13
+ // }
14
+ // },
15
+ connect : ( ) => ( Component ) => Component
16
+ } ) )
17
+
18
+ test ( 'Main' , ( ) => {
19
+ const { container } = render ( < Main /> )
20
+ expect ( container . textContent ) . toBe ( '2' )
21
+ } )
Original file line number Diff line number Diff line change
1
+ export const useDispatch = ( ) => undefined
2
+ export const useSelector = ( ) => undefined
You can’t perform that action at this time.
0 commit comments