i'm using react-native-testing-library to test some react native components and those act warnings are driving me insane.
Use case:
- Load
Screeninside react-navigation. - Using
useFocusEffect, agetrequest is made to backend by usingaxios.ScreenshowsActivityIndicatorwhile loading. Screenshows aFlatListwith objects in response.
Component:
import * as React from 'react'
import axios from 'axios'
import { useFocusEffect } from '@react-navigation/native'
...
const Screen = ({ navigation }) => {
const [data, setData] = React.useState([])
const [loading, setLoading] = React.useState(false)
const loadData = React.useCallback(() => {
setLoading(true)
axios.get('url').then(response => {
setData(response.data)
setLoading(false)
})
}, [])
const focusView = React.useCallback(() => {
loadData()
}, [loadData])
const unfocusView = React.useCallback(() => {
setData([])
setLoading(false)
}, [])
useFocusEffect(
React.useCallback(() => {
focusView()
return unfocusView
}, [focusView, unfocusView])
)
return <JSX with proper testID>
}
...
export default Screen
Test:
import * as React from 'react'
import { render, screen, waitFor } from '@testing-library/react-native'
import axios from 'axios'
import { NavigationContainer } from '@react-navigation/native'
import Screen fom '@screens/Screen'
jest.mock('axios')
test('shows a list of resource', async () => {
const response = {
data: [
{id: 0, name: 'Thing 1'},
{id: 0, name: 'Thing 2'}
]
}
axios.get.mockResolvedValueOnce(response)
const navigation = {}
render(<NavigationContainer><Screen navigation={navigation} /></NavigationContainer>)
expect(await screen.findByTextId('_loading')).not.toBe(null)
expect(await screen.findByTextId('_resources_list')).not.toBe(null)
})
I have been trying for a while and this version of the example seems to pass but always show some kind of warning You called act(() => ...) without await.