【问题标题】:Can't find named elements with react-native-testing-library使用 react-native-testing-library 找不到命名元素
【发布时间】:2021-04-07 07:07:39
【问题描述】:

我试图通过占位符文本获取元素,但 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');.

它运行顺利,但它不应该。

我不确定自己做错了什么。

【问题讨论】:

  • 我相信你真正想要的是expect(getByPlaceholderText('Cirurgião')).toBeInTheDocument();。这将测试您的 &lt;input /&gt; 元素与 placheholder 文本 'Cirurgião' 是否已呈现。

标签: react-native unit-testing react-testing-library react-native-testing-library


【解决方案1】:

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');

【讨论】:

  • 非常感谢您的回答。它对我有用,尝试使用 testID 或 value 等其他道具进行测试,但效果一样。
猜你喜欢
  • 2022-08-06
  • 2019-03-30
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
相关资源
最近更新 更多