Skip to content

Commit f7f2103

Browse files
committed
feat: improve stack traces for throwable methods
1 parent 129bda8 commit f7f2103

File tree

1 file changed

+42
-12
lines changed

1 file changed

+42
-12
lines changed

src/index.js

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,18 +33,39 @@ export const render = (
3333
const renderer = TestRenderer.create(component, options);
3434
const instance = renderer.root;
3535

36+
const getByName = (name: string | React.Element<*>) => {
37+
try {
38+
return instance.find(node => getNodeByName(node, name));
39+
} catch (error) {
40+
throw new ErrorWithStack(`Error: Component not found.`, getByName);
41+
}
42+
};
43+
44+
const getByText = (text: string | RegExp) => {
45+
try {
46+
return instance.find(node => getNodeByText(node, text));
47+
} catch (error) {
48+
throw new ErrorWithStack(`Error: Component not found.`, getByText);
49+
}
50+
};
51+
52+
const getByProps = (props: { [propName: string]: any }) => {
53+
try {
54+
return instance.findByProps(props);
55+
} catch (error) {
56+
throw new ErrorWithStack(`Error: Component not found.`, getByProps);
57+
}
58+
};
59+
3660
return {
3761
getByTestId: (testID: string) => instance.findByProps({ testID }),
38-
getByName: (name: string | React.Element<*>) =>
39-
instance.find(node => getNodeByName(node, name)),
62+
getByName,
4063
getAllByName: (name: string | React.Element<*>) =>
4164
instance.findAll(node => getNodeByName(node, name)),
42-
getByText: (text: string | RegExp) =>
43-
instance.find(node => getNodeByText(node, text)),
65+
getByText,
4466
getAllByText: (text: string | RegExp) =>
4567
instance.findAll(node => getNodeByText(node, text)),
46-
getByProps: (props: { [propName: string]: any }) =>
47-
instance.findByProps(props),
68+
getByProps,
4869
getAllByProps: (props: { [propName: string]: any }) =>
4970
instance.findAllByProps(props),
5071
update: renderer.update,
@@ -79,10 +100,19 @@ export const debug = (
79100
) => {
80101
const { output } = shallow(instance);
81102
// eslint-disable-next-line no-console
82-
console.log(
83-
prettyFormat(output, {
84-
plugins: [plugins.ReactTestComponent, plugins.ReactElement],
85-
}),
86-
message || ''
87-
);
103+
console.log(format(output), message || '');
88104
};
105+
106+
const format = input =>
107+
prettyFormat(input, {
108+
plugins: [plugins.ReactTestComponent, plugins.ReactElement],
109+
});
110+
111+
class ErrorWithStack extends Error {
112+
constructor(message: ?string, callsite: Function) {
113+
super(message);
114+
if (Error.captureStackTrace) {
115+
Error.captureStackTrace(this, callsite);
116+
}
117+
}
118+
}

0 commit comments

Comments
 (0)