Skip to content

Commit b919fde

Browse files
author
Peter Hozak
committed
exercise 06 (without live demo)
1 parent 296c466 commit b919fde

File tree

4 files changed

+55
-4
lines changed

4 files changed

+55
-4
lines changed

08-testing-hooks/README.md

+12-4
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,18 @@ Simplify tests with react-testing-library:
6464
- replace modification of input value
6565

6666

67-
## 05 react-redux
67+
## 05 mock API data and timers
6868
> [src/05](src/05)
6969
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
7373

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)
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
})
+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const useDispatch = () => undefined
2+
export const useSelector = () => undefined

0 commit comments

Comments
 (0)