使用 React-native 时,为什么会收到错误“接收到的值必须是 HTMLElement 或 SVGElement”?

the*_*rar 22 jestjs react-native react-native-testing-library jest-dom

我是单元测试的新手,我正在尝试渲染一个组件以了解有关该库的更多信息。

我正在尝试遵循指南。

成分

<TouchableOpacity
    style={style}
    onPress={onPress}
    accessibilityRole="button"
>
    <AppText style={textStyle}>{title.toUpperCase()}</AppText>
</TouchableOpacity> 
Run Code Online (Sandbox Code Playgroud)

测试

it("Has the correct title in the button", () => {
    const { getByText } = render(<AppButton title="Hello" />);
  
    expect(getByText("HELLO")).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)

我只是想查看组件是否正确渲染,但出现错误

received value must be an HTMLElement or an SVGElement.
    Received has type:  object
    Received has value: {"_fiber": {"_debugHookTypes": null, "_debugID": 40, "_debugIsCurrentlyTiming": false, "_debugNeedsRemount": false, "_debugOwner": [FiberNode], "_debugSource": null, "actualDuration": 0, "actualStartTime": -1, "alternate": null, "child": [FiberNode], "childExpirationTime": 0, "dependencies": null, "effectTag": 1, "elementType": [Function Component], "expirationTime": 0, "firstEffect": null, "index": 0, "key": null, "lastEffect": null, "memoizedProps": [Object], "memoizedState": null, "mode": 0, "nextEffect": null, "pendingProps": [Object], "ref": null, "return": [FiberNode], "selfBaseDuration": 0, "sibling": null, "stateNode": [Component], "tag": 1, "treeBaseDuration": 0, "type": [Function Component], "updateQueue": [Object]}}
Run Code Online (Sandbox Code Playgroud)

对我做错了什么有什么建议吗?

小智 27

您可以使用waitFor

样本:

import { waitFor } from "@testing-library/react-native";


waitFor(() => expect(getByText("Your-text")).toBeInTheDocument());

// or

waitFor(() => expect(getByTestId("Your-Test-Id")).toBeInTheDocument());
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`waitFor()` 是异步的,因此您的测试应该 ```await waitFor(() =&gt; Expect(getByText("Your-text")).toBeInTheDocument());``` (2认同)

jul*_*ves 15

问题是您正在尝试使用React Native 代码toBeInTheDocument中的辅助函数@testing-library/jest-dom@testing-library/jest-dom期望将 DOM 元素传递给其函数,并且应该使用 with@testing-library/react来代替 - 它不能与 React Native 中的原生元素一起使用。

使用时,@testing-library/react-native您可以像这样断言元素的存在。

it("has the correct title in the button", () => {
    const { getByText } = render(<AppButton title="Hello" />);
    expect(getByText("HELLO")).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)