简体   繁体   English

React Native:如何测试元素是否聚焦?

[英]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:要检查一个元素是否专注于带有 RTL 和 jest 的 react web 应用程序,您可以使用两个简单的选项:

  1. You can check if the element is the same as document.activeElement (may have to discard some wrappers)您可以检查元素是否与 document.activeElement 相同(可能必须丢弃一些包装器)
  2. You can extend your jest matchers with https://github.com/testing-library/jest-dom#tohavefocus and use expect(<element>).toHaveFocus()您可以使用https://github.com/testing-library/jest-dom#tohavefocus扩展您的笑话匹配器并使用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).我不确定 react native 的等效检查是什么(与 jest-dom 扩展等效的 RN 是https://github.com/testing-library/jest-native并且明显缺少toHaveFocus匹配器)。

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 .据我所知, React Native 测试库没有这个匹配器, Jest Native 匹配器扩展器也没有。

It looks like Detox supports it though.看起来Detox支持它。

There are lots of suggestions to use refs (which might let us call ref.current.isFocused()), or capture onFocus\onBlur events.有很多使用 refs 的建议(这可能让我们调用 ref.current.isFocused()),或者捕获 onFocus\onBlur 事件。 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当元素没有被聚焦时, ref 完全消失了

Regarding, tracking onFocus\onBlur, it's unnecessary overhead and only further complicates the production code for the sake of testing.关于跟踪 onFocus\onBlur,这是不必要的开销,并且为了测试只会使生产代码更加复杂。 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 .我决定在 Jest Native 项目中打开一个功能请求 Cross your fingers.交叉你的手指。

React.js users have it so easy! React.js 用户使用起来非常简单!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM