微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法使用 react-native-testing-library 找到命名元素

如何解决无法使用 react-native-testing-library 找到命名元素

我正在尝试通过占位符文本获取元素,但 react-native-testing-library 不断向我抛出相同的错误

expect(received).toEqual(expected) // deep equality

    Expected: "Cirurgião"
    Received: {"_fiber": {"_debugHookTypes": null,"_debugID": 451,"_debugIsCurrentlyTiming": 
false,"_debugNeedsRemount": false,"_debugOwner": [FiberNode],"_debugSource": [Object],"actualDuration": 0,"actualStartTime": -1,"alternate": null,"child": [FiberNode],"childExpirationTime": 0,"dependencies": null,"effectTag": 129,"elementType": [Function 
Component],"expirationTime": 0,"firstEffect": null,"index": 0,"key": null,"lastEffect":
 null,"memoizedProps": [Object],"memoizedState": null,"mode": 0,"nextEffect": null,"pendingProps": [Object],"ref": [Function ref],"return": [FiberNode],"selfBaseDuration": 0,"sibling": null,"stateNode": [Component],"tag": 1,"treeBaseDuration": 0,"type": [Function 
Component],"updateQueue": null}}


这是我要测试的代码

const { getByTestId,queryByTestId,getByPlaceholderText} = render(
      <Input placeholder="Cirurgião"
        testID='input_buscaCirurgiao_index'
        value={mockValue}
        autoCorrect={false}
        keyboardType={(Platform.OS === 'android') ? 'visible-password' : 'default'}
        onChangeText={mockState}
        onSubmitEditing={mockState}
        autoCapitalize='none' />
    );

    expect(getByPlaceholderText('Cirurgião')).toEqual('Cirurgião');

我还尝试通过 getByTestId 和 queryByTestId 获取我要测试的元素,但两者都出现了类似的错误

如果我尝试使用 waitFor() => 进行测试,我不会收到任何错误消息,即使我尝试更改预期的输出,如 expect(getByTestId('test1').toEqual('test2');.

它运行顺利,但不应该。

我不确定我做错了什么。

解决方法

getByPlaceholderText 返回 first matching node。事实上,它成功地做到了这一点。节点表示为一个对象,你的测试说

    Expected: "Cirurgião"
    Received: {"_fiber": { //<- Here you actually received an object representing the node

发生这种情况是因为您希望对象节点等于一个字符串(字符串 != 节点):

.toEqual('Cirurgião');

您可能想要测试两种可能的情况:

  1. 组件是否真的存在/正在渲染?
  2. 视图是否包含我期望的占位符?

要测试第一个,您只需执行以下操作:

getByPlaceholderText('Cirurgião')

如果渲染树中没有组件,它将抛出异常,因此您的测试将失败。

测试第二个将是:

const input = getByPlaceholderText('Cirurgião');
expect(input.props.placeholder).toBe('Cirurgião');

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?