Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: How to test if element is focused?

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).

like image 838
Jimmy Gong Avatar asked Nov 16 '22 00:11

Jimmy Gong


1 Answers

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!

like image 151
cchapin Avatar answered Dec 15 '22 20:12

cchapin