React Native: How to test if element is focused?
Asked Answered
B

1

9

Simply test case: Want to see if a given element is focused.

To check if an element is focused on a react web app with RTL and jest, you have two easy options available to you:

  1. You can check if the element is the same as document.activeElement (may have to discard some wrappers)
  2. You can extend your jest matchers with https://github.com/testing-library/jest-dom#tohavefocus and use expect(<element>).toHaveFocus()

I'm not sure what the equivalent check would be with react native (the RN equivalent to the jest-dom extension is https://github.com/testing-library/jest-native and is conspicuously missing the toHaveFocus matcher).

Brownedoff answered 25/1, 2021 at 18:0 Comment(1)
Related: Test Focus of ElementAcutance
L
5

Sunk several hours in to this today. From what I can see, React Native Testing Library doesn't have this matcher and neither does the Jest Native matcher extender.

It looks like Detox supports it though.

There are lots of suggestions to use refs (which might let us call ref.current.isFocused()), or capture onFocus\onBlur events. But these aren't viable from the test environment perspective.

There were 2 things I observed with the refs.

  1. The refs all get mocked out in jest (I don't know enough about jest to know why).
  2. When the element is not focused, the ref is completely gone

Regarding, tracking onFocus\onBlur, it's unnecessary overhead and only further complicates the production code for the sake of testing. Then the component has to accept these as props and a mock has to be created for each one... no thanks!

I decided to open a feature request in the Jest Native project. Cross your fingers.

React.js users have it so easy!

Leyden answered 31/1, 2022 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.