-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathcreateTestHarness.tsx
68 lines (58 loc) · 2.15 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
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
import React, { Suspense } from 'react'
import { ErrorBoundary, FallbackProps } from 'react-error-boundary'
import filterConsole from 'filter-console'
import { addCleanup } from '../core'
import { RendererProps, WrapperComponent } from '../types/react'
function suppressErrorOutput() {
// The error output from error boundaries is notoriously difficult to suppress. To save
// out users from having to work it out, we crudely suppress the output matching the patterns
// below. For more information, see these issues:
// - https://github.com/testing-library/react-hooks-testing-library/issues/50
// - https://github.com/facebook/react/issues/11098#issuecomment-412682721
// - https://github.com/facebook/react/issues/15520
// - https://github.com/facebook/react/issues/18841
const removeConsoleFilter = filterConsole(
[
/^The above error occurred in the <TestComponent> component:/, // error boundary output
/^Error: Uncaught .+/ // jsdom output
],
{
methods: ['error']
}
)
addCleanup(removeConsoleFilter)
}
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
}
suppressErrorOutput()
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 }