mirror of
https://github.com/callstack/react-native-testing-library.git
synced 2026-09-18 23:09:04 +08:00
97ab842567
### Summary
Given a component that renders text by composing together literal text with an inline expression for a dynamic variable, React Native will render this as a `<Text>` element with multiple children. For example:
```js
const BananaCounter = ({ numBananas }) => (
<Text>There are {numBananas} bananas in the bunch</Text>
);
const { toJSON, debug } = render(<BananaCounter numBananas={3} />);
debug();
/*
<Text>
There are
3
bananas in the bunch
</Text>
*/
expect(toJSON()).toMatchInlineSnapshot(`
<Text>
There are
3
bananas in the bunch
</Text>
`);
```
This makes sense, as the component is a:
- literal string
- a dynamic evaluation
- literal string
Unfortunately, this means that writing a test that finds an element based on that dynamic evaluation fails when using `getByText`.
```js
const { getByText } = render(<BananaCounter numBananas={3} />);
expect(getByText('There are 3 bananas in the bunch')).toBeTruthy(); // Fails
```
This is because we compare the given test string directly against `children`. https://github.com/callstack/react-native-testing-library/blob/ce3bf28f308728672bc5502e120048821c60218b/src/helpers/getByAPI.js#L23-L24
This results in comparing `'There are 3 bananas in the bunch' === ['There are ' 3, ' bananas in the bunch']`, which of course will fail.
The solution is to join children and compare the joined result against the given text string.
### Test plan
A test for this new functionality is provided!