![](/img/trans.png)
[英]When testing, code that causes React state updates should be wrapped into act
[英]When testing, code that causes React state updates should be wrapped into act(...) - with simple react-native nested screen/components with jest axios
我是單元測試/玩笑的新手,但我知道一些關於本機反應的知識。 我想為我的 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
幾天前發生在我身上的fireEvent
。 嘗試這個:
await waitFor(()=> render(<HomeScreen />))
您遇到問題的原因是因為 state 正在發生變化。 在第一次渲染時,apiResponse 數據設置為 null。 后來在 api 響應中, apiResponse 有一個值,因此發生了重新渲染,所以開玩笑地抱怨它。
要解決,您可以使用await waitFor(() => expect(api).toHaveBeenCalledTimes(1))
。 這將等待一段特定的時間。
建議:在測試中模擬你的 api,而不是直接點擊它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.