Testing the pressed state of a Pressable

Viewed 957

I have a component that renders a React Native Pressable and uses the pressed state to alter the display:

<Pressable testID="t">
  {({ pressed }) => <Text style={pressed ? pressedStyle : unPressedStyle }>{title}</Text>
<Pressable>

This works fine, but when I run a test coverage report, the pressed state is skipped. This happens even if I fire a press event on the pressable, for example:

const { getByTestID } = render(<PressableComponent />);
const pressable = getByTestID('t');
fireEvent.press(pressable);

Is there any way to trigger the pressed state during testing so that I can test that branch?

1 Answers

You can use the testOnly_pressed property of RN Pressable component. If set to true it simulates a pressed state in tests.

<Pressable testID="t" testOnly_pressed={isStatusPressedForTest}>
  {({ pressed }) => <Text style={pressed ? pressedStyle : unPressedStyle }>{title}</Text>
<Pressable>


const { getByTestID } = render(<PressableComponent isStatusPressedForTest />);

No need to fire the press event then anymore. Just expect what you expect to happen in status pressed.

Related