Skip to content

Feat : emulate string outside text error #1070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
8c87340
feat: throw an error when a text is rendered outside a component on r…
Aug 19, 2022
1ecdf97
feat: check on every rerender if strings are rendered outside Text
Aug 20, 2022
913a54f
feat: change error message thrown so it is clearer
Aug 23, 2022
4bdf998
refactor: rename function assertStringsWithinTextOnUpdate with a shor…
Aug 23, 2022
925233e
refactor: move test from fireEvent tests to render tests
Aug 29, 2022
eb5f03a
tests: add test case for string validation with string nested in frag…
Aug 29, 2022
7b79ce6
refactor: use an object for render params
Aug 29, 2022
1786fd6
feat: add an option false by default for string validation
Aug 29, 2022
d3f8fa7
refactor: rewrite method hasNodeStringChild using Array.some
Aug 29, 2022
2d497f4
fix: also throw an error when a number is rendered outside text or wi…
Aug 29, 2022
3181513
add skipped test for failing validation
Aug 29, 2022
9a545ca
refactor: rename variable in assertStringsWithinText for more coherence
Aug 30, 2022
883e478
refactor: use the json representation for validating strings rendered…
Aug 30, 2022
dba3554
tests: override console.error to hide profiler error messages
Aug 31, 2022
0608359
feat: change name of option for string validation to experimentalVali…
Aug 31, 2022
72ca097
refactor: rename experimentalValidateStringsRenderedInText option to …
Sep 3, 2022
c235e7b
refactor: extract function assertStringsWithinTextForNode from assert…
Sep 3, 2022
b5eec79
fix: validate strings also inside of text components
Sep 3, 2022
bbcac9f
tests: use pressable instead of touchable in render tests
Sep 3, 2022
f6a5be6
refactor: extract profiler error message in a variable
Sep 3, 2022
69a8852
tests: add another test case for string validation
Sep 3, 2022
6333cce
refactor: export a single render function for better readability
Sep 3, 2022
92ff852
feat: add informations in validation string error messages
Sep 3, 2022
5b3c94b
feat: change error message to match more closely original message of rn
Sep 18, 2022
8a46e01
refactor: dont call assertStringsWithinText in assertStringsWithinTex…
Sep 18, 2022
e2ec15d
refactor: rename enrichRenderResult to buildRenderResult
Sep 18, 2022
f59eaa3
refactor: change naming for more consistency
Sep 18, 2022
82c254d
refactor: rename string validation function to match option name
Sep 18, 2022
aacc77f
refactor: change name of the option to be closer to rn error message
Sep 18, 2022
60b8be6
refactor: make render test names single line
Sep 19, 2022
57f9917
refactor: extract validate strings tests into separate file
mdjastrzebski Sep 19, 2022
ba21380
chore: tweak file naming
mdjastrzebski Sep 19, 2022
417c2ba
chore: file naming consistency
mdjastrzebski Sep 19, 2022
e8890fd
refactor: final tweaks
mdjastrzebski Sep 19, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 58 additions & 21 deletions src/__tests__/__snapshots__/render.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,15 @@ exports[`debug 1`] = `
accessible={true}
collapsable={false}
focusable={true}
onBlur={[Function onBlur]}
onClick={[Function onClick]}
onFocus={[Function onFocus]}
onResponderGrant={[Function onResponderGrant]}
onResponderMove={[Function onResponderMove]}
onResponderRelease={[Function onResponderRelease]}
onResponderTerminate={[Function onResponderTerminate]}
onResponderTerminationRequest={[Function onResponderTerminationRequest]}
onStartShouldSetResponder={[Function onStartShouldSetResponder]}
style={
Object {
"opacity": 1,
}
}
>
<Text>
Change freshness!
Expand Down Expand Up @@ -97,18 +94,15 @@ exports[`debug changing component: bananaFresh button message should now be "fre
accessible={true}
collapsable={false}
focusable={true}
onBlur={[Function onBlur]}
onClick={[Function onClick]}
onFocus={[Function onFocus]}
onResponderGrant={[Function onResponderGrant]}
onResponderMove={[Function onResponderMove]}
onResponderRelease={[Function onResponderRelease]}
onResponderTerminate={[Function onResponderTerminate]}
onResponderTerminationRequest={[Function onResponderTerminationRequest]}
onStartShouldSetResponder={[Function onStartShouldSetResponder]}
style={
Object {
"opacity": 1,
}
}
>
<Text>
Change freshness!
Expand Down Expand Up @@ -266,18 +260,15 @@ exports[`debug: with message 1`] = `
accessible={true}
collapsable={false}
focusable={true}
onBlur={[Function onBlur]}
onClick={[Function onClick]}
onFocus={[Function onFocus]}
onResponderGrant={[Function onResponderGrant]}
onResponderMove={[Function onResponderMove]}
onResponderRelease={[Function onResponderRelease]}
onResponderTerminate={[Function onResponderTerminate]}
onResponderTerminationRequest={[Function onResponderTerminationRequest]}
onStartShouldSetResponder={[Function onStartShouldSetResponder]}
style={
Object {
"opacity": 1,
}
}
>
<Text>
Change freshness!
Expand All @@ -299,23 +290,69 @@ exports[`debug: with message 1`] = `
</View>"
`;

exports[`it should throw
- when one of the children is a text
- and the parent is not a Text component 1`] = `
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "hello" string within a <View> component."
`;

exports[`it should throw
- when a string is rendered within a fragment rendered outside a Text 1`] = `
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "hello" string within a <View> component."
`;

exports[`it should throw if a number is rendered outside a text:
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "0" string within a <View> component."
1`] = `
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "0" string within a <View> component."
`;

exports[`it should throw when rendering string in a View in a Text 1`] = `
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "hello" string within a <View> component."
`;

exports[`should throw an error when rerendering with text outside of Text component 1`] = `
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "hello" string within a <View> component."
`;

exports[`should throw an error when strings are rendered outside Text 1`] = `
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "text rendered outside text component" string within a <View> component."
`;

exports[`should throw when rendering a string outside a text component 1`] = `
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "hello" string within a <View> component."
`;

exports[`toJSON 1`] = `
<View
accessible={true}
collapsable={false}
focusable={false}
focusable={true}
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onResponderGrant={[Function]}
onResponderMove={[Function]}
onResponderRelease={[Function]}
onResponderTerminate={[Function]}
onResponderTerminationRequest={[Function]}
onStartShouldSetResponder={[Function]}
style={
{
"opacity": 1,
}
}
>
<Text>
press me
Expand Down
165 changes: 156 additions & 9 deletions src/__tests__/render.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import * as React from 'react';
import {
View,
Text,
TextInput,
TouchableOpacity,
SafeAreaView,
} from 'react-native';
import { View, Text, TextInput, Pressable, SafeAreaView } from 'react-native';
import stripAnsi from 'strip-ansi';
import { render, fireEvent, RenderAPI } from '..';

const originalConsoleError = console.error;

type ConsoleLogMock = jest.Mock<Array<string>>;

const PLACEHOLDER_FRESHNESS = 'Add custom freshness';
Expand All @@ -21,9 +17,9 @@ const DEFAULT_INPUT_CUSTOMER = 'What banana?';
class MyButton extends React.Component<any> {
render() {
return (
<TouchableOpacity onPress={this.props.onPress}>
<Pressable onPress={this.props.onPress}>
<Text>{this.props.children}</Text>
</TouchableOpacity>
</Pressable>
);
}
}
Expand Down Expand Up @@ -283,3 +279,154 @@ test('RenderAPI type', () => {
render(<Banana />) as RenderAPI;
expect(true).toBeTruthy();
});

test('should throw when rendering a string outside a text component', () => {
expect(() =>
render(<View>hello</View>, {
unstable_validateStringsRenderedWithinText: true,
})
).toThrowErrorMatchingSnapshot();
});

const profilerErrorMessage =
'The above error occurred in the <Profiler> component';

test('should throw an error when rerendering with text outside of Text component', () => {
// eslint-disable-next-line no-console
console.error = (errorMessage: string) => {
if (!errorMessage.includes(profilerErrorMessage)) {
originalConsoleError(errorMessage);
}
};
const { rerender } = render(<View />, {
unstable_validateStringsRenderedWithinText: true,
});

expect(() => rerender(<View>hello</View>)).toThrowErrorMatchingSnapshot();

// eslint-disable-next-line no-console
console.error = originalConsoleError;
});

const ErrorComponent = () => {
const [shouldDisplayText, setShouldDisplayText] = React.useState(false);

if (!shouldDisplayText) {
return (
<Pressable
onPress={() => {
setShouldDisplayText(true);
}}
>
<Text>Display text</Text>
</Pressable>
);
}

return <View>text rendered outside text component</View>;
};

test('should throw an error when strings are rendered outside Text', () => {
// eslint-disable-next-line no-console
console.error = (errorMessage: string) => {
if (!errorMessage.includes(profilerErrorMessage)) {
originalConsoleError(errorMessage);
}
};
const { getByText } = render(<ErrorComponent />, {
unstable_validateStringsRenderedWithinText: true,
});

expect(() =>
fireEvent.press(getByText('Display text'))
).toThrowErrorMatchingSnapshot();

// eslint-disable-next-line no-console
console.error = originalConsoleError;
});

test('it should not throw for texts nested in fragments', () => {
expect(() =>
render(
<Text>
<>hello</>
</Text>,
{ unstable_validateStringsRenderedWithinText: true }
)
).not.toThrow();
});

test('it should not throw if option validateRenderedString is false', () => {
expect(() => render(<View>hello</View>)).not.toThrow();
});

test(`it should throw
- when one of the children is a text
- and the parent is not a Text component`, () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
test(`it should throw
- when one of the children is a text
- and the parent is not a Text component`, () => {
test(`it should throw when one of the children is a text and the parent is not a Text component`, () => {

expect(() =>
render(
<View>
<Text>hello</Text>
hello
</View>,
{ unstable_validateStringsRenderedWithinText: true }
)
).toThrowErrorMatchingSnapshot();
});

test(`it should throw
- when a string is rendered within a fragment rendered outside a Text`, () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

```suggestion when a string is rendered within a fragment rendered outside a Text`, () => {

expect(() =>
render(
<View>
<>hello</>
</View>,
{ unstable_validateStringsRenderedWithinText: true }
)
).toThrowErrorMatchingSnapshot();
});

test('it should throw if a number is rendered outside a text', () => {
expect(() =>
render(<View>0</View>, { unstable_validateStringsRenderedWithinText: true })
).toThrowErrorMatchingSnapshot(`
"Invariant Violation: Text strings must be rendered within a <Text> component.

Detected attempt to render "0" string within a <View> component."
`);
});

const Trans = ({ i18nKey }: { i18nKey: string }) => <>{i18nKey}</>;

test('it should throw with components returning string value not rendered in Text', () => {
expect(() =>
render(
<View>
<Trans i18nKey="hello" />
</View>,
{ unstable_validateStringsRenderedWithinText: true }
)
).toThrow();
});

test('it should not throw with components returning string value rendered in Text', () => {
expect(() =>
render(
<Text>
<Trans i18nKey="hello" />
</Text>,
{ unstable_validateStringsRenderedWithinText: true }
)
).not.toThrow();
});

test('it should throw when rendering string in a View in a Text', () => {
expect(() =>
render(
<Text>
<View>hello</View>
</Text>,
{ unstable_validateStringsRenderedWithinText: true }
)
).toThrowErrorMatchingSnapshot();
});
36 changes: 36 additions & 0 deletions src/helpers/validateStringsRenderedWithinText.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { ReactTestRendererNode } from 'react-test-renderer';

export const validateStringsRenderedWithinText = (
rendererJSON: ReactTestRendererNode | Array<ReactTestRendererNode> | null
) => {
if (!rendererJSON) return;

if (Array.isArray(rendererJSON)) {
rendererJSON.forEach(validateStringsRenderedWithinTextForNode);
return;
}

return validateStringsRenderedWithinTextForNode(rendererJSON);
};

const validateStringsRenderedWithinTextForNode = (
node: ReactTestRendererNode
) => {
if (typeof node === 'string') {
return;
}

if (node.type !== 'Text') {
node.children?.forEach((child) => {
if (typeof child === 'string') {
throw new Error(
`Invariant Violation: Text strings must be rendered within a <Text> component.\n\nDetected attempt to render "${child}" string within a <${node.type}> component.`
);
}
});
}

if (node.children) {
node.children.forEach(validateStringsRenderedWithinTextForNode);
}
};
Loading