我是单元测试/玩笑的新手,但我知道一些关于本机反应的知识。我想为我的 HomeScreen 编写一个测试,其中包含一个发出简单请求的组件。代码运行没有任何问题,但当我用 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
我试图弄清楚为什么它一直说我应该把它包装起来,我到底需要包装什么?我已经尝试将渲染整行包装,但没有成功。
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