Replace invariant with console.error in View

Jest dumps the invariant error to the console when unit tests run, which is
both annoying and more likely to cause unwanted error to go unnoticed. We're
also moving away from using 'invariant' in React. This patch replaces the
invariant with a call to 'console.error', which won't crash an app that is
using raw text nodes as View children, but it's better than nothing.
This commit is contained in:
Nicolas Gallagher
2019-12-21 16:58:14 +00:00
parent 287251a06a
commit 16c0109df6
2 changed files with 27 additions and 17 deletions
@@ -10,13 +10,28 @@ describe('components/View', () => {
expect(container.firstChild).toMatchSnapshot();
});
test('text node throws error (single)', () => {
const subject = () => render(<View>hello</View>);
expect(subject).toThrow();
test('non-text is rendered', () => {
const children = <View testID="1" />;
const { container } = render(<View>{children}</View>);
expect(container.firstChild).toMatchSnapshot();
});
test('text node throws error (array)', () => {
const subject = () =>
describe('raw text nodes as children', () => {
beforeEach(() => {
jest.spyOn(console, 'error');
console.error.mockImplementation(() => {});
});
afterEach(() => {
console.error.mockRestore();
});
test('error logged (single)', () => {
render(<View>hello</View>);
expect(console.error).toBeCalled();
});
test('error logged (array)', () => {
render(
<View>
<View />
@@ -24,13 +39,8 @@ describe('components/View', () => {
<View />
</View>
);
expect(subject).toThrow();
});
test('non-text is rendered', () => {
const children = <View testID="1" />;
const { container } = render(<View>{children}</View>);
expect(container.firstChild).toMatchSnapshot();
expect(console.error).toBeCalled();
});
});
describe('prop "hitSlop"', () => {
+5 -5
View File
@@ -15,7 +15,6 @@ import applyNativeMethods from '../../modules/applyNativeMethods';
import createElement from '../createElement';
import css from '../StyleSheet/css';
import filterSupportedProps from './filterSupportedProps';
import invariant from 'fbjs/lib/invariant';
import StyleSheet from '../StyleSheet';
import TextAncestorContext from '../Text/TextAncestorContext';
import React from 'react';
@@ -42,10 +41,11 @@ class View extends React.Component<ViewProps> {
if (process.env.NODE_ENV !== 'production') {
React.Children.toArray(this.props.children).forEach(item => {
invariant(
typeof item !== 'string',
`Unexpected text node: ${item}. A text node cannot be a child of a <View>.`
);
if (typeof item === 'string') {
console.error(
`Unexpected text node: ${item}. A text node cannot be a child of a <View>.`
);
}
});
}