-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrenderHookToSnapshotStream.test.tsx
74 lines (70 loc) · 2.24 KB
/
renderHookToSnapshotStream.test.tsx
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
/* eslint-disable no-await-in-loop */
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import {EventEmitter} from 'node:events'
import {scheduler} from 'node:timers/promises'
import {test, expect} from '@jest/globals'
import {renderHookToSnapshotStream} from '@testing-library/react-render-stream'
import * as React from 'react'
const testEvents = new EventEmitter<{
rerenderWithValue: [unknown]
}>()
function useRerenderEvents(initialValue: unknown) {
const lastValueRef = React.useRef(initialValue)
return React.useSyncExternalStore(
onChange => {
const cb = (value: unknown) => {
lastValueRef.current = value
onChange()
}
testEvents.addListener('rerenderWithValue', cb)
return () => {
testEvents.removeListener('rerenderWithValue', cb)
}
},
() => {
return lastValueRef.current
},
)
}
test('basic functionality', async () => {
const {takeSnapshot} = await renderHookToSnapshotStream(useRerenderEvents, {
initialProps: 'initial',
})
testEvents.emit('rerenderWithValue', 'value')
await scheduler.wait(10)
testEvents.emit('rerenderWithValue', 'value2')
{
const snapshot = await takeSnapshot()
expect(snapshot).toBe('initial')
}
{
const snapshot = await takeSnapshot()
expect(snapshot).toBe('value')
}
{
const snapshot = await takeSnapshot()
expect(snapshot).toBe('value2')
}
})
test.each<[type: string, initialValue: unknown, ...nextValues: unknown[]]>([
['string', 'initial', 'value', 'value2'],
['number', 0, 1, 2],
['functions', () => {}, () => {}, function named() {}],
['objects', {a: 1}, {a: 2}, {foo: 'bar'}],
['arrays', [1], [1, 2], [2]],
['null/undefined', null, undefined, null],
['undefined/null', undefined, null, undefined],
])('works with %s', async (_, initialValue, ...nextValues) => {
const {takeSnapshot} = await renderHookToSnapshotStream(useRerenderEvents, {
initialProps: initialValue,
})
for (const nextValue of nextValues) {
testEvents.emit('rerenderWithValue', nextValue)
// allow for a render to happen
await Promise.resolve()
}
expect(await takeSnapshot()).toBe(initialValue)
for (const nextValue of nextValues) {
expect(await takeSnapshot()).toBe(nextValue)
}
})