在react-native detox中如何根据祖先元素的索引匹配对应子元素
解决方案
核心思路是调整匹配器的执行顺序,将索引直接绑定到祖先元素的匹配规则上,再传入withAncestor,就能实现你要的「先定位指定索引的祖先元素,再在其后代查询子元素」的逻辑。
修改后的封装代码如下:
export const noteCardDescriptor = (baseID: string) => (index: number) => { // 提前构造带索引的祖先匹配器,直接锁定第index个目标卡片 const targetCardMatcher = by.id(baseID).atIndex(index); return { get element() { return element(targetCardMatcher); }, get title() { return element(by.id('NoteCardTitle').withAncestor(targetCardMatcher)); }, get date() { return element(by.id('NoteCardDate').withAncestor(targetCardMatcher)); }, }; }; class MyScreen { static note = noteCardDescriptor('MyScreenNoteCard') }
效果说明
- 所有子元素的查询范围被严格限制在你指定索引的那张卡片内,即使其他卡片缺少对应可选元素,也不会出现索引错位匹配的问题
- 完全保留你原有的调用方式,上层测试代码不需要做任何修改,可读性和之前一致
- 匹配逻辑完全符合你预期的
element(by.id(X).withAncestor(by.id(Y).atIndex(0)))写法要求
内容的提问来源于stack exchange,提问作者Gabriel Rohden
相关产品推荐
相关产品推荐

