最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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!

发布评论

评论列表(0)

  1. 暂无评论