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 all 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
30 changes: 9 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 @@ -303,19 +294,16 @@ 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
157 changes: 157 additions & 0 deletions src/__tests__/render-stringValidation.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import * as React from 'react';
import { View, Text, Pressable } from 'react-native';
import { render, fireEvent } from '..';

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

const VALIDATION_ERROR =
'Invariant Violation: Text strings must be rendered within a <Text> component';
const PROFILER_ERROR = 'The above error occurred in the <Profiler> component';

beforeEach(() => {
// eslint-disable-next-line no-console
console.error = (errorMessage: string) => {
if (!errorMessage.includes(PROFILER_ERROR)) {
originalConsoleError(errorMessage);
}
};
});

afterEach(() => {
// eslint-disable-next-line no-console
console.error = originalConsoleError;
});

test('should throw when rendering a string outside a text component', () => {
expect(() =>
render(<View>hello</View>, {
unstable_validateStringsRenderedWithinText: true,
})
).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "hello" string within a <View> component.`
);
});

test('should throw an error when rerendering with text outside of Text component', () => {
const { rerender } = render(<View />, {
unstable_validateStringsRenderedWithinText: true,
});

expect(() => rerender(<View>hello</View>)).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "hello" string within a <View> component.`
);
});

const InvalidTextAfterPress = () => {
const [showText, setShowText] = React.useState(false);

if (!showText) {
return (
<Pressable onPress={() => setShowText(true)}>
<Text>Show text</Text>
</Pressable>
);
}

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

test('should throw an error when strings are rendered outside Text', () => {
const { getByText } = render(<InvalidTextAfterPress />, {
unstable_validateStringsRenderedWithinText: true,
});

expect(() => fireEvent.press(getByText('Show text'))).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "text rendered outside text component" string within a <View> component.`
);
});

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

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

test(`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 }
)
).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "hello" string within a <View> component.`
);
});

test(`should throw when a string is rendered within a fragment rendered outside a Text`, () => {
expect(() =>
render(
<View>
<>hello</>
</View>,
{ unstable_validateStringsRenderedWithinText: true }
)
).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "hello" string within a <View> component.`
);
});

test('should throw if a number is rendered outside a text', () => {
expect(() =>
render(<View>0</View>, { unstable_validateStringsRenderedWithinText: true })
).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "0" string within a <View> component.`
);
});

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

test('should throw with components returning string value not rendered in Text', () => {
expect(() =>
render(
<View>
<Trans i18nKey="hello" />
</View>,
{ unstable_validateStringsRenderedWithinText: true }
)
).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "hello" string within a <View> component.`
);
});

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

test('should throw when rendering string in a View in a Text', () => {
expect(() =>
render(
<Text>
<View>hello</View>
</Text>,
{ unstable_validateStringsRenderedWithinText: true }
)
).toThrow(
`${VALIDATION_ERROR}. Detected attempt to render "hello" string within a <View> component.`
);
});
12 changes: 3 additions & 9 deletions src/__tests__/render.test.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
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 '..';

Expand All @@ -21,9 +15,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
36 changes: 36 additions & 0 deletions src/helpers/stringValidation.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. Detected attempt to render "${child}" string within a <${node.type}> component.`
);
}
});
}

if (node.children) {
node.children.forEach(validateStringsRenderedWithinTextForNode);
}
};
59 changes: 55 additions & 4 deletions src/render.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import TestRenderer from 'react-test-renderer';
import type { ReactTestInstance, ReactTestRenderer } from 'react-test-renderer';
import * as React from 'react';
import { Profiler } from 'react';
import act from './act';
import { addToCleanupQueue } from './cleanup';
import debugShallow from './helpers/debugShallow';
import debugDeep from './helpers/debugDeep';
import { getQueriesForElement } from './within';
import { setRenderResult } from './screen';
import { setRenderResult, screen } from './screen';
import { validateStringsRenderedWithinText } from './helpers/stringValidation';

export type RenderOptions = {
wrapper?: React.ComponentType<any>;
createNodeMock?: (element: React.ReactElement) => any;
unstable_validateStringsRenderedWithinText?: boolean;
};

type TestRendererOptions = {
Expand All @@ -25,17 +28,65 @@ export type RenderResult = ReturnType<typeof render>;
*/
export default function render<T>(
component: React.ReactElement<T>,
{ wrapper: Wrapper, createNodeMock }: RenderOptions = {}
{
wrapper: Wrapper,
createNodeMock,
unstable_validateStringsRenderedWithinText,
}: RenderOptions = {}
) {
const wrap = (innerElement: React.ReactElement) =>
Wrapper ? <Wrapper>{innerElement}</Wrapper> : innerElement;
if (unstable_validateStringsRenderedWithinText) {
return renderWithStringValidation(component, {
wrapper: Wrapper,
createNodeMock,
});
}

const wrap = (element: React.ReactElement) =>
Wrapper ? <Wrapper>{element}</Wrapper> : element;

const renderer = renderWithAct(
wrap(component),
createNodeMock ? { createNodeMock } : undefined
);

return buildRenderResult(renderer, wrap);
}

function renderWithStringValidation<T>(
component: React.ReactElement<T>,
{
wrapper: Wrapper,
createNodeMock,
}: Omit<RenderOptions, 'unstable_validateStringsRenderedWithinText'> = {}
) {
const handleRender: React.ProfilerProps['onRender'] = (_, phase) => {
if (phase === 'update') {
validateStringsRenderedWithinText(screen.toJSON());
}
};

const wrap = (element: React.ReactElement) => (
<Profiler id="renderProfiler" onRender={handleRender}>
{Wrapper ? <Wrapper>{element}</Wrapper> : element}
</Profiler>
);

const renderer = renderWithAct(
wrap(component),
createNodeMock ? { createNodeMock } : undefined
);
validateStringsRenderedWithinText(renderer.toJSON());

return buildRenderResult(renderer, wrap);
}

function buildRenderResult(
renderer: ReactTestRenderer,
wrap: (element: React.ReactElement) => JSX.Element
) {
const update = updateWithAct(renderer, wrap);
const instance = renderer.root;

const unmount = () => {
act(() => {
renderer.unmount();
Expand Down