Skip to content

Commit afa7c8e

Browse files
committed
Add test to ensure we are calling selector on state change
1 parent 9a28e78 commit afa7c8e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

test/hooks/useSelector.spec.tsx

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,49 @@ describe('React', () => {
319319
expect(numCalls).toBe(2)
320320
expect(renderedItems.length).toEqual(2)
321321
})
322+
323+
it('calls selector twice once on mount when state changes during render', () => {
324+
interface StateType {
325+
count: number
326+
}
327+
const store = createStore(({ count }: StateType = { count: 0 }) => ({
328+
count: count + 1,
329+
}))
330+
331+
let numCalls = 0
332+
const selector = (s: StateType) => {
333+
numCalls += 1
334+
return s.count
335+
}
336+
const renderedItems = []
337+
338+
const Child = () => {
339+
useLayoutEffect(() => {
340+
store.dispatch({ type: '', count: 1 })
341+
}, [])
342+
return <div />
343+
}
344+
345+
const Comp = () => {
346+
const value = useSelector(selector)
347+
renderedItems.push(value)
348+
return (
349+
<div>
350+
<Child />
351+
</div>
352+
)
353+
}
354+
355+
rtl.render(
356+
<ProviderMock store={store}>
357+
<Comp />
358+
</ProviderMock>
359+
)
360+
361+
// Selector first called on Comp mount, and then re-invoked after mount due to useLayoutEffect dispatching event
362+
expect(numCalls).toBe(2)
363+
expect(renderedItems.length).toEqual(2)
364+
})
322365
})
323366

324367
it('uses the latest selector', () => {

0 commit comments

Comments
 (0)