When I test component containing TouchableOpacity
with React-Native
testing library, first time render is ok, second time in test suite test always fails.
If I replace TouchableOpacity
with TouchableWithoutFeedback
, render will go ok. Other animated Touchable's
fail too.
The tested component
import { TouchableOpacity, Text } from 'react-native';
const TestedComponent = () => (
<TouchableOpacity testID="tested-component">
<Text>Button</Text>
</TouchableOpacity>
);
The tests (two are identical)
describe('TestedComponent', () => {
test('should render TestedComponent', () => {
render(<TestedComponent />);
expect(screen.getByTestId('tested-component')).toBeVisible();
});
test('should render TestedComponent', () => {
render(<TestedComponent />);
expect(screen.getByTestId('tested-component')).toBeVisible();
});
});
First one passes second fails. When I change their order — the same happens
Error I get
console.error
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
16 |
17 | test('should render TestedComponent', () => {
> 18 | render(<TestedComponent />, {
| ^
19 | createNodeMock: () => {},
20 | });
21 |
And one more
The above error occurred in the <ForwardRef> component:
at /Users/tetyana/Documents/UWRead/Codebase/uwr-mobile/node_modules/react-native/Libraries/Animated/createAnimatedComponent.js:36:57
at TouchableOpacity (/Users/tetyana/Documents/UWRead/Codebase/uwr-mobile/node_modules/react-native/Libraries/Components/Touchable/TouchableOpacity.js:132:23)
at TouchableOpacity
at TestedComponent
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
16 |
17 | test('should render TestedComponent', () => {
> 18 | render(<TestedComponent />, {
| ^
19 | createNodeMock: () => {},
20 | });
21 |
And one more
● TestedComponent › should render TestedComponent
TypeError: Cannot read properties of null (reading 'useReducer')
16 |
17 | test('should render TestedComponent', () => {
> 18 | render(<TestedComponent />, {
| ^
19 | createNodeMock: () => {},
20 | });
21 |
I tried different components, as well as browsing React
, React-Native
and testing library docs, do different types of cleanups but with no result.
Can someone please help?
I found the culprit. I had setupTests.js running where was a block
It caused the failure.