-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathrender.tsx
96 lines (85 loc) · 2.41 KB
/
render.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import TestRenderer from 'react-test-renderer';
import type { ReactTestInstance, ReactTestRenderer } from 'react-test-renderer';
import * as React from 'react';
import act from './act';
import { addToCleanupQueue } from './cleanup';
import debugShallow from './helpers/debugShallow';
import debugDeep from './helpers/debugDeep';
import { getQueriesForElement } from './within';
type Options = {
wrapper?: React.ComponentType<any>;
createNodeMock?: (element: React.ReactElement) => any;
};
type TestRendererOptions = {
createNodeMock: (element: React.ReactElement) => any;
};
/**
* Renders test component deeply using react-test-renderer and exposes helpers
* to assert on the output.
*/
export default function render<T>(
component: React.ReactElement<T>,
{ wrapper: Wrapper, createNodeMock }: Options = {}
) {
const wrap = (innerElement: React.ReactElement) =>
Wrapper ? <Wrapper>{innerElement}</Wrapper> : innerElement;
const renderer = renderWithAct(
wrap(component),
createNodeMock ? { createNodeMock } : undefined
);
const update = updateWithAct(renderer, wrap);
const instance = renderer.root;
const unmount = () => {
act(() => {
renderer.unmount();
});
};
addToCleanupQueue(unmount);
return {
...getQueriesForElement(instance),
update,
unmount,
container: instance,
rerender: update, // alias for `update`
toJSON: renderer.toJSON,
debug: debug(instance, renderer),
};
}
function renderWithAct(
component: React.ReactElement,
options?: TestRendererOptions
): ReactTestRenderer {
let renderer: ReactTestRenderer;
act(() => {
renderer = TestRenderer.create(component, options);
});
// @ts-ignore act is sync, so renderer is always initialised here
return renderer;
}
function updateWithAct(
renderer: ReactTestRenderer,
wrap: (innerElement: React.ReactElement) => React.ReactElement
) {
return function (component: React.ReactElement) {
act(() => {
renderer.update(wrap(component));
});
};
}
interface DebugFunction {
(message?: string): void;
shallow: (message?: string) => void;
}
function debug(
instance: ReactTestInstance,
renderer: ReactTestRenderer
): DebugFunction {
function debugImpl(message?: string) {
const json = renderer.toJSON();
if (json) {
return debugDeep(json, message);
}
}
debugImpl.shallow = (message?: string) => debugShallow(instance, message);
return debugImpl;
}