首页 > 解决方案 > 如何在 React Native 中使用 toBeVisible 匹配器

问题描述

我正在react-native-testing-library使用"@testing-library/jest-dom/extend-expect".

看起来toBeVisible只适用于 ReactJS:

const nameField = component.getByPlaceholder("Name");
expect(nameField).toBeVisible();

// Test Error:
● NewCustomerScreen › the basics › encountered a declaration exception

    expect(received).toBeVisible()

    received value must be an HTMLElement or an SVGElement.
    Received has type:  object
    Received has value: {"_fiber": {"_debugHookTypes": null, "_debugID": 26, "_debugIsCurrentlyTiming": false, "_debugOwner": [FiberNode], "_debugSource": null, "alternate": null, "child": [FiberNode], "childExpirationTime": 0, "contextDependencies": null, "effectTag": 133, "elementType": [Function Component], "expirationTime": 0, "firstEffect": null, "index": 1, "key": null, "lastEffect": null, "memoizedProps": [Object], "memoizedState": null, "mode": 0, "nextEffect": [FiberNode], "pendingProps": [Object], "ref": [Function ref], "return": [FiberNode], "sibling": null, "stateNode": [Component], "tag": 1, "type": [Function Component], "updateQueue": null}}

有没有办法让它工作?

标签: react-native

解决方案


你可以用这个

在这里你可以看到与此相关的解释。

import { render } from 'react-native-testing-library';
...
const { getByPlaceholder } = render(
  <View>
    <TextInput placeholder="Name"  />
  </View>
);
..
expect(getByPlaceholder("Name")).toBeVisible();

可见示例

<View>
  <View testID="not-empty">
    <Text testID="empty" />
  </View>
  <Text testID="visible">Visible Example</Text>
</View>;

expect(queryByTestId(baseElement, 'not-empty')).not.toBeEmpty();
expect(getByText(baseElement, 'Visible Example')).toBeVisible();

推荐阅读