-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathcreateTestHarness.tsx
43 lines (36 loc) · 1.25 KB
/
createTestHarness.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
import React, { Suspense } from 'react'
import { ErrorBoundary, FallbackProps } from 'react-error-boundary'
import { RendererProps, WrapperComponent } from '../types/react'
function createTestHarness<TProps, TResult>(
{ callback, setValue, setError }: RendererProps<TProps, TResult>,
Wrapper?: WrapperComponent<TProps>,
suspense: boolean = true
) {
const TestComponent = ({ hookProps }: { hookProps?: TProps }) => {
// coerce undefined into TProps, so it maintains the previous behaviour
setValue(callback(hookProps as TProps))
return null
}
let resetErrorBoundary = () => {}
const ErrorFallback = ({ error, resetErrorBoundary: reset }: FallbackProps) => {
resetErrorBoundary = () => {
resetErrorBoundary = () => {}
reset()
}
setError(error)
return null
}
const testHarness = (props?: TProps) => {
resetErrorBoundary()
let component = <TestComponent hookProps={props} />
if (Wrapper) {
component = <Wrapper {...(props as TProps)}>{component}</Wrapper>
}
if (suspense) {
component = <Suspense fallback={null}>{component}</Suspense>
}
return <ErrorBoundary FallbackComponent={ErrorFallback}>{component}</ErrorBoundary>
}
return testHarness
}
export { createTestHarness }