-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathhost-component-names.tsx
75 lines (62 loc) · 2.38 KB
/
host-component-names.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
import * as React from 'react';
import { ReactTestInstance } from 'react-test-renderer';
import { Switch, Text, TextInput, View } from 'react-native';
import { configureInternal, getConfig, HostComponentNames } from '../config';
import { renderWithAct } from '../render-act';
const userConfigErrorMessage = `There seems to be an issue with your configuration that prevents React Native Testing Library from working correctly.
Please check if you are using compatible versions of React Native and React Native Testing Library.`;
export function getHostComponentNames(): HostComponentNames {
let hostComponentNames = getConfig().hostComponentNames;
if (!hostComponentNames) {
hostComponentNames = detectHostComponentNames();
configureInternal({ hostComponentNames });
}
return hostComponentNames;
}
export function configureHostComponentNamesIfNeeded() {
const configHostComponentNames = getConfig().hostComponentNames;
if (configHostComponentNames) {
return;
}
const hostComponentNames = detectHostComponentNames();
configureInternal({ hostComponentNames });
}
function detectHostComponentNames(): HostComponentNames {
try {
const renderer = renderWithAct(
<View>
<Text testID="text">Hello</Text>
<TextInput testID="textInput" />
<Switch testID="switch" />
</View>
);
return {
text: getByTestId(renderer.root, 'text').type as string,
textInput: getByTestId(renderer.root, 'textInput').type as string,
switch: getByTestId(renderer.root, 'switch').type as string,
};
} catch (error) {
const errorMessage =
error && typeof error === 'object' && 'message' in error
? error.message
: null;
throw new Error(
`Trying to detect host component names triggered the following error:\n\n${errorMessage}\n\n${userConfigErrorMessage}`
);
}
}
function getByTestId(instance: ReactTestInstance, testID: string) {
const nodes = instance.findAll(
(node) => typeof node.type === 'string' && node.props.testID === testID
);
if (nodes.length === 0) {
throw new Error(`Unable to find an element with testID: ${testID}`);
}
return nodes[0];
}
export function isHostText(element?: ReactTestInstance) {
return element?.type === getHostComponentNames().text;
}
export function isHostTextInput(element?: ReactTestInstance) {
return element?.type === getHostComponentNames().textInput;
}