-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncView.test.tsx
More file actions
90 lines (78 loc) · 2.11 KB
/
Copy pathAsyncView.test.tsx
File metadata and controls
90 lines (78 loc) · 2.11 KB
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
import React from 'react'
import { render, RenderResult } from '@testing-library/react'
import { AsyncView } from '../AsyncView'
type Data = {
greeting: string
} | null
type Error = {
message: string
}
const Loading: React.FC = () => {
return <>Loading</>
}
const Success: React.FC<{ data: Data }> = ({ data }) => {
return <>{data?.greeting}</>
}
const Error: React.FC<{ error: Error }> = ({ error }) => {
return <>{error.message}</>
}
type RenderAsyncViewProps = {
isLoading: boolean
error?: Error
data?: Data
allowMissingData?: boolean
}
function renderAsyncView({
isLoading,
data,
error,
allowMissingData = false,
}: RenderAsyncViewProps): RenderResult {
return render(
<AsyncView
isLoading={isLoading}
data={data}
error={error}
allowMissingData={allowMissingData}
renderLoading={<Loading />}
renderSuccess={(data: unknown) => <Success data={data as Data} />}
renderError={(error) => <Error error={error} />}
/>,
)
}
test('should render loading if asyncState is loading for the first time', function () {
const { getByText } = renderAsyncView({ isLoading: true })
expect(getByText(/loading/i)).toBeInTheDocument()
})
test('should render success if asyncState is successful', function () {
const { getByText } = renderAsyncView({
isLoading: false,
data: { greeting: 'Hello' },
})
expect(getByText(/hello/i)).toBeInTheDocument()
})
test.each([null, undefined])(
'should throw asyncState is successful but data is missing',
function (value) {
expect(() => renderAsyncView({ isLoading: false, data: value })).toThrow()
},
)
test.each([null, undefined])(
'should render success if asyncState is successful but data is missing but allowed',
function (value) {
expect(() =>
renderAsyncView({
isLoading: false,
data: value,
allowMissingData: true,
}),
).not.toThrow()
},
)
test('should render error if asyncState is error', function () {
const { getByText } = renderAsyncView({
isLoading: false,
error: { message: 'Error' },
})
expect(getByText(/error/i)).toBeInTheDocument()
})