forked from callstack/react-native-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.js
84 lines (74 loc) · 2.32 KB
/
render.js
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
// @flow
import * as React from 'react';
import TestRenderer, { type ReactTestRenderer } from 'react-test-renderer'; // eslint-disable-line import/no-extraneous-dependencies
import act from './act';
import { addToCleanupQueue } from './cleanup';
import { getByAPI } from './helpers/getByAPI';
import { queryByAPI } from './helpers/queryByAPI';
import { findByAPI } from './helpers/findByAPI';
import a11yAPI from './helpers/a11yAPI';
import debugShallow from './helpers/debugShallow';
import debugDeep from './helpers/debugDeep';
type Options = {
wrapper?: React.ComponentType<any>,
createNodeMock?: (element: React.Element<any>) => any,
};
type TestRendererOptions = {
createNodeMock: (element: React.Element<any>) => any,
};
/**
* Renders test component deeply using react-test-renderer and exposes helpers
* to assert on the output.
*/
export default function render<T>(
component: React.Element<T>,
{ wrapper: Wrapper, createNodeMock }: Options = {}
) {
const wrap = (innerElement: React.Element<any>) =>
Wrapper ? <Wrapper>{innerElement}</Wrapper> : innerElement;
const renderer = renderWithAct(
wrap(component),
createNodeMock ? { createNodeMock } : undefined
);
const update = updateWithAct(renderer, wrap);
const instance = renderer.root;
addToCleanupQueue(renderer.unmount);
return {
...getByAPI(instance),
...queryByAPI(instance),
...findByAPI(instance),
...a11yAPI(instance),
update,
rerender: update, // alias for `update`
unmount: renderer.unmount,
toJSON: renderer.toJSON,
debug: debug(instance, renderer),
};
}
function renderWithAct(
component: React.Element<any>,
options?: TestRendererOptions
): ReactTestRenderer {
let renderer: ReactTestRenderer;
act(() => {
renderer = TestRenderer.create(component, options);
});
return ((renderer: any): ReactTestRenderer);
}
function updateWithAct(
renderer: ReactTestRenderer,
wrap: (innerElement: React.Element<any>) => React.Element<any>
) {
return function (component: React.Element<any>) {
act(() => {
renderer.update(wrap(component));
});
};
}
function debug(instance: ReactTestInstance, renderer) {
function debugImpl(message?: string) {
return debugDeep(renderer.toJSON(), message);
}
debugImpl.shallow = (message) => debugShallow(instance, message);
return debugImpl;
}