Skip to content

Commit

Permalink
fix: improve the error message for incorrect screen configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
satya164 committed Nov 10, 2020
1 parent f8e998b commit 8f764d8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
45 changes: 45 additions & 0 deletions packages/core/src/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1462,6 +1462,51 @@ it('throws when Screen is not the direct children', () => {
);
});

it('throws when undefined component is a direct children', () => {
const TestNavigator = (props: any) => {
useNavigationBuilder(MockRouter, props);
return null;
};

const Undefined = undefined;

const spy = jest.spyOn(console, 'error').mockImplementation();
const element = (
<BaseNavigationContainer>
<TestNavigator>
{/* @ts-ignore */}
<Undefined name="foo" component={jest.fn()} />
</TestNavigator>
</BaseNavigationContainer>
);

spy.mockRestore();

expect(() => render(element).update(element)).toThrowError(
"A navigator can only contain 'Screen' components as its direct children (found 'undefined' for the screen 'foo')"
);
});

it('throws when a tag is a direct children', () => {
const TestNavigator = (props: any) => {
useNavigationBuilder(MockRouter, props);
return null;
};

const element = (
<BaseNavigationContainer>
<TestNavigator>
{/* @ts-ignore */}
<screen name="foo" component={jest.fn()} />
</TestNavigator>
</BaseNavigationContainer>
);

expect(() => render(element).update(element)).toThrowError(
"A navigator can only contain 'Screen' components as its direct children (found 'screen' for the screen 'foo')"
);
});

it('throws when a React Element is not the direct children', () => {
const TestNavigator = (props: any) => {
useNavigationBuilder(MockRouter, props);
Expand Down
15 changes: 11 additions & 4 deletions packages/core/src/useNavigationBuilder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,17 @@ const getRouteConfigsFromChildren = <
}

throw new Error(
`A navigator can only contain 'Screen' components as its direct children (found '${
// @ts-expect-error: child can be any type and we're accessing it safely, but TS doesn't understand it
child.type?.name ? child.type.name : String(child)
}'). To render this component in the navigator, pass it in the 'component' prop to 'Screen'.`
`A navigator can only contain 'Screen' components as its direct children (found ${
React.isValidElement(child)
? `'${
typeof child.type === 'string' ? child.type : child.type?.name
}'${
child.props?.name ? ` for the screen '${child.props.name}'` : ''
}`
: typeof child === 'object'
? JSON.stringify(child)
: `'${String(child)}'`
}). To render this component in the navigator, pass it in the 'component' prop to 'Screen'.`
);
}, []);

Expand Down

0 comments on commit 8f764d8

Please sign in to comment.