javascript - React Native: How to test if element is focused? - Stack Overflow

Simply test case: Want to see if a given element is focused.To check if an element is focused on a rea

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 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 and is conspicuously missing the toHaveFocus matcher).

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./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./testing-library/jest-native and is conspicuously missing the toHaveFocus matcher).

Share Improve this question asked Jan 25, 2021 at 18:00 Jimmy GongJimmy Gong 1,9655 gold badges21 silver badges36 bronze badges 1
  • Related: Test Focus of Element – ggorlen Commented Nov 7, 2021 at 4:49
Add a ment  | 

1 Answer 1

Reset to default 6

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 pletely gone

Regarding, tracking onFocus\onBlur, it's unnecessary overhead and only further plicates the production code for the sake of testing. Then the ponent 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!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744892234a4599485.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信