forked from reduxjs/react-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseSelector.spec.js
512 lines (397 loc) · 14 KB
/
useSelector.spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*eslint-disable react/prop-types*/
import React, { useCallback, useReducer, useLayoutEffect } from 'react'
import { createStore } from 'redux'
import { renderHook, act } from '@testing-library/react-hooks'
import * as rtl from '@testing-library/react'
import {
Provider as ProviderMock,
useSelector,
shallowEqual,
connect,
createSelectorHook,
} from '../../src/index'
import { useReduxContext } from '../../src/hooks/useReduxContext'
describe('React', () => {
describe('hooks', () => {
describe('useSelector', () => {
let store
let renderedItems = []
beforeEach(() => {
store = createStore(({ count } = { count: -1 }) => ({
count: count + 1,
}))
renderedItems = []
})
afterEach(() => rtl.cleanup())
describe('core subscription behavior', () => {
it('selects the state on initial render', () => {
const { result } = renderHook(() => useSelector((s) => s.count), {
wrapper: (props) => <ProviderMock {...props} store={store} />,
})
expect(result.current).toEqual(0)
})
it('selects the state and renders the component when the store updates', () => {
const selector = jest.fn((s) => s.count)
const { result } = renderHook(() => useSelector(selector), {
wrapper: (props) => <ProviderMock {...props} store={store} />,
})
expect(result.current).toEqual(0)
expect(selector).toHaveBeenCalledTimes(2)
act(() => {
store.dispatch({ type: '' })
})
expect(result.current).toEqual(1)
expect(selector).toHaveBeenCalledTimes(3)
})
})
describe('lifecycle interactions', () => {
it('always uses the latest state', () => {
store = createStore((c) => c + 1, -1)
const Comp = () => {
const selector = useCallback((c) => c + 1, [])
const value = useSelector(selector)
renderedItems.push(value)
return <div />
}
rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
expect(renderedItems).toEqual([1])
store.dispatch({ type: '' })
expect(renderedItems).toEqual([1, 2])
})
it('subscribes to the store synchronously', () => {
let rootSubscription
const Parent = () => {
const { subscription } = useReduxContext()
rootSubscription = subscription
const count = useSelector((s) => s.count)
return count === 1 ? <Child /> : null
}
const Child = () => {
const count = useSelector((s) => s.count)
return <div>{count}</div>
}
rtl.render(
<ProviderMock store={store}>
<Parent />
</ProviderMock>
)
expect(rootSubscription.getListeners().get().length).toBe(1)
store.dispatch({ type: '' })
expect(rootSubscription.getListeners().get().length).toBe(2)
})
it('unsubscribes when the component is unmounted', () => {
let rootSubscription
const Parent = () => {
const { subscription } = useReduxContext()
rootSubscription = subscription
const count = useSelector((s) => s.count)
return count === 0 ? <Child /> : null
}
const Child = () => {
const count = useSelector((s) => s.count)
return <div>{count}</div>
}
rtl.render(
<ProviderMock store={store}>
<Parent />
</ProviderMock>
)
expect(rootSubscription.getListeners().get().length).toBe(2)
store.dispatch({ type: '' })
expect(rootSubscription.getListeners().get().length).toBe(1)
})
it('notices store updates between render and store subscription effect', () => {
const Comp = () => {
const count = useSelector((s) => s.count)
renderedItems.push(count)
// I don't know a better way to trigger a store update before the
// store subscription effect happens
if (count === 0) {
store.dispatch({ type: '' })
}
return <div>{count}</div>
}
rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
expect(renderedItems).toEqual([0, 1])
})
})
it('works properly with memoized selector with dispatch in Child useLayoutEffect', () => {
store = createStore((c) => c + 1, -1)
const Comp = () => {
const selector = useCallback((c) => c, [])
const count = useSelector(selector)
renderedItems.push(count)
return <Child parentCount={count} />
}
const Child = ({ parentCount }) => {
useLayoutEffect(() => {
if (parentCount === 1) {
store.dispatch({ type: '' })
}
}, [parentCount])
return <div>{parentCount}</div>
}
rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
// The first render doesn't trigger dispatch
expect(renderedItems).toEqual([0])
// This dispatch triggers another dispatch in useLayoutEffect
rtl.act(() => {
store.dispatch({ type: '' })
})
expect(renderedItems).toEqual([0, 1, 2])
})
describe('performance optimizations and bail-outs', () => {
it('defaults to ref-equality to prevent unnecessary updates', () => {
const state = {}
store = createStore(() => state)
const Comp = () => {
const value = useSelector((s) => s)
renderedItems.push(value)
return <div />
}
rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
expect(renderedItems.length).toBe(1)
store.dispatch({ type: '' })
expect(renderedItems.length).toBe(1)
})
it('allows other equality functions to prevent unnecessary updates', () => {
store = createStore(
({ count, stable } = { count: -1, stable: {} }) => ({
count: count + 1,
stable,
})
)
const Comp = () => {
const value = useSelector((s) => Object.keys(s), shallowEqual)
renderedItems.push(value)
return <div />
}
rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
expect(renderedItems.length).toBe(1)
store.dispatch({ type: '' })
expect(renderedItems.length).toBe(1)
})
})
it('uses the latest selector', () => {
let selectorId = 0
let forceRender
const Comp = () => {
const [, f] = useReducer((c) => c + 1, 0)
forceRender = f
const renderedSelectorId = selectorId++
const value = useSelector(() => renderedSelectorId)
renderedItems.push(value)
return <div />
}
rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
expect(renderedItems).toEqual([0])
rtl.act(forceRender)
expect(renderedItems).toEqual([0, 1])
rtl.act(() => {
store.dispatch({ type: '' })
})
expect(renderedItems).toEqual([0, 1])
rtl.act(forceRender)
expect(renderedItems).toEqual([0, 1, 2])
})
describe('edge cases', () => {
it('ignores transient errors in selector (e.g. due to stale props)', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
const Parent = () => {
const count = useSelector((s) => s.count)
return <Child parentCount={count} />
}
const Child = ({ parentCount }) => {
const result = useSelector(({ count }) => {
if (count !== parentCount) {
throw new Error()
}
return count + parentCount
})
return <div>{result}</div>
}
rtl.render(
<ProviderMock store={store}>
<Parent />
</ProviderMock>
)
expect(() => store.dispatch({ type: '' })).not.toThrowError()
spy.mockRestore()
})
it('correlates the subscription callback error with a following error during rendering', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
const Comp = () => {
const result = useSelector((count) => {
if (count > 0) {
throw new Error('foo')
}
return count
})
return <div>{result}</div>
}
const store = createStore((count = -1) => count + 1)
const App = () => (
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
rtl.render(<App />)
expect(() => store.dispatch({ type: '' })).toThrow(
/The error may be correlated/
)
spy.mockRestore()
})
it('re-throws errors from the selector that only occur during rendering', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
const Parent = () => {
const count = useSelector((s) => s.count)
return <Child parentCount={count} />
}
const Child = ({ parentCount }) => {
const result = useSelector(({ count }) => {
if (parentCount > 0) {
throw new Error()
}
return count + parentCount
})
return <div>{result}</div>
}
rtl.render(
<ProviderMock store={store}>
<Parent />
</ProviderMock>
)
expect(() => store.dispatch({ type: '' })).toThrowError()
spy.mockRestore()
})
it('allows dealing with stale props by putting a specific connected component above the hooks component', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
const Parent = () => {
const count = useSelector((s) => s.count)
return <ConnectedWrapper parentCount={count} />
}
const ConnectedWrapper = connect(({ count }) => ({ count }))(
({ parentCount }) => {
return <Child parentCount={parentCount} />
}
)
let sawInconsistentState = false
const Child = ({ parentCount }) => {
const result = useSelector(({ count }) => {
if (count !== parentCount) {
sawInconsistentState = true
}
return count + parentCount
})
return <div>{result}</div>
}
rtl.render(
<ProviderMock store={store}>
<Parent />
</ProviderMock>
)
store.dispatch({ type: '' })
expect(sawInconsistentState).toBe(false)
spy.mockRestore()
})
it('reuse latest selected state on selector re-run', () => {
store = createStore(({ count } = { count: -1 }) => ({
count: count + 1,
}))
const alwaysEqual = () => true
const Comp = () => {
// triggers render on store change
useSelector((s) => s.count)
const array = useSelector(() => [1, 2, 3], alwaysEqual)
renderedItems.push(array)
return <div />
}
rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)
expect(renderedItems.length).toBe(1)
store.dispatch({ type: '' })
expect(renderedItems.length).toBe(2)
expect(renderedItems[0]).toBe(renderedItems[1])
})
})
describe('error handling for invalid arguments', () => {
it('throws if no selector is passed', () => {
expect(() => useSelector()).toThrow()
})
it('throws if selector is not a function', () => {
expect(() => useSelector(1)).toThrow()
})
it('throws if equality function is not a function', () => {
expect(() => useSelector((s) => s.count, 1)).toThrow()
})
})
})
describe('createSelectorHook', () => {
let defaultStore
let customStore
beforeEach(() => {
defaultStore = createStore(({ count } = { count: -1 }) => ({
count: count + 1,
}))
customStore = createStore(({ count } = { count: 10 }) => ({
count: count + 2,
}))
})
it('subscribes to the correct store', () => {
const nestedContext = React.createContext(null)
const useCustomSelector = createSelectorHook(nestedContext)
let defaultCount = null
let customCount = null
const getCount = (s) => s.count
const DisplayDefaultCount = ({ children = null }) => {
const count = useSelector(getCount)
defaultCount = count
return <>{children}</>
}
const DisplayCustomCount = ({ children = null }) => {
const count = useCustomSelector(getCount)
customCount = count
return <>{children}</>
}
rtl.render(
<ProviderMock store={defaultStore}>
<ProviderMock context={nestedContext} store={customStore}>
<DisplayCustomCount>
<DisplayDefaultCount />
</DisplayCustomCount>
</ProviderMock>
</ProviderMock>
)
expect(defaultCount).toBe(0)
expect(customCount).toBe(12)
})
})
})
})