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

Dom*_*olt 2 reactjs jestjs react-native testing-libraryreact-native

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

主屏.js

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

HomeScreen.test.js

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

it('should run', async () => {
    const { getByText } = await render(<HomeScreen />)
})
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我试图弄清楚为什么它一直说我应该将其包装在 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
Run Code Online (Sandbox Code Playgroud)

Ale*_*oyo 5

fireEvent几天前这件事发生在我身上。尝试这个:

await waitFor(()=> render(<HomeScreen />))
Run Code Online (Sandbox Code Playgroud)