reactjs - 测试时,导致 React 状态更新的代码应该包装到 act(...) 中 - 使用简单的 React-native 嵌套屏幕/组件和 jest axios

标签 reactjs react-native jestjs testing-libraryreact-native

我是单元测试/Jest 的新手,但我对 React Native 了解一些。 我想为我的主屏幕编写一个测试,其中包含一个发出简单请求的组件。代码运行没有任何问题,但当我用 Jest 运行它时失败。

HomeScreen.js

import { View } from 'react-native'
import APIExample from '@components/Examples/APIExample'
const HomeScreen = () => {
    return (<View> <APIExample /> </View>)
}
export default HomeScreen

HomeScreen.test.js

import { render } from '@testing-library/react-native'
import HomeScreen from '@screens/HomeScreen'

it('should run', async () => {
    const { getByText } = await render(<HomeScreen />)
})

APIExample.js

import { useState, useEffect } from 'react'
import { Text, View } from 'react-native'
import API from '../../API'

const APIExample = () => {
    const [apiResponse, setApiResponse] = useState(null)

    const Submit = async () => {
        const response = await API.Test()
        setApiResponse(response)
    }
    useEffect(() => {
        Submit()
    }, [])
    return (
        <View>
            <Text>
                {JSON.stringify(apiResponse)}
            </Text>
        </View>
    )
}
export default APIExample

我试图弄清楚为什么它一直说我应该将其包装在 act 中,以及我到底需要包装什么? 我已经尝试将渲染整行包装起来,但没有成功。

API.Test 是一个简单的 axios.get

我一直收到的错误是:

Warning: An update to APIExample inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act

最佳答案

几天前,我在 fireEvent 中发生了这种情况。试试这个:

await waitFor(()=> render(<HomeScreen />))

关于reactjs - 测试时,导致 React 状态更新的代码应该包装到 act(...) 中 - 使用简单的 React-native 嵌套屏幕/组件和 jest axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70684277/

相关文章:

javascript - 抽屉不适用于 `mdl-layout--fixed-header` 类

reactjs - React MUI V5 AppBar 背景颜色不改变

javascript - ReactNative - 许多应用程序使用相同的 JS 代码

jestjs - Jest+React 原生测试库 : How to test an image src?

jestjs - 如何使用 Jest 模拟外部模块的功能

CSSTransition 在 css 网格布局中制作滑出式抽屉

javascript - ReactJS:当触发 onChange 时,我如何知道从组件自动传递了哪些参数?

typescript - 如何在模拟函数时允许部分 TypeScript 类型 - Jest、TypeScript

android - React Native GeoLocation 不适用于 Android

react-native - 如何防止我的 ImageBackground 在 React Native 中调整大小?