I want to query an element through jest which is conditionally rendered. The component is rendered after loading state is set to false when Api call is complete. There are ways to query elements which are rendered after an event such as button press or text input focus. But I am unable to find a way to query element which is rendered after a state change when Api call is complete.
Component:
const Home = ({navigation}) => {
const dispatch = useDispatch();
const {user, orders} = useSelector(state => state.user);
const [loading, setLoading] = useState(true);
const getOrders = () => {
fetch(`http://192.168.1.17:6000/users/${user.userId}/orders`)
.then(res => res.json())
.then(orders => {
dispatch(setOrders(orders));
setLoading(false);
})
.catch(err => console.log(err));
};
const getUser = () => {
fetch(`http://192.168.1.17:6000/users/${user.userId}`)
.then(res => res.json())
.then(user => {
dispatch(setUserInfo(user));
getOrders();
})
.catch(err => console.log(err));
};
ListEmptyComponent = () => (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Lottie
source={require('../../assets/empty-box')}
style={{height: 200}}
autoPlay
loop={false}
/>
<Text style={{fontWeight: 'bold', fontSize: 14}}>No Orders Assigned</Text>
</View>
);
useEffect(() => {
getUser();
}, []);
return loading ? (
<ActivityIndicator
style={{flex: 1, alignSelf: 'center'}}
size={26}
color={'#4D61D6'}
/>
) : (
<View
testID="test"
style={{
flex: 1,
padding: 20,
backgroundColor: '#ECECEC',
}}>
{orders.length > 0 && (
<TouchableOpacity
testID="qrCodeButton"
onPress={() => navigation.navigate('Scan Order')}
style={{
alignSelf: 'center',
padding: 20,
backgroundColor: '#4D61D6',
marginBottom: 30,
borderRadius: 3,
}}>
<Text style={{color: 'white', fontWeight: 'bold'}}>
Scan Order QR Code
</Text>
</TouchableOpacity>
)}
<FlatList
data={orders}
testID={'orderComponent'}
contentContainerStyle={{flex: 1}}
ListEmptyComponent={ListEmptyComponent}
renderItem={({item}) =>
!item.is_verified && (
<OrderComponent
key={item.entity_id}
item={item}
navigation={navigation}
/>
)
}
/>
</View>
);
};
export default Home;
Test Case:
it('Show Button to scan order QR Code', () => {
const {queryByTestId} = render(
<Provider store={store}>
<Home loading={false} />
</Provider>,
);
expect(queryByTestId('qrCodeButton')).toBeTruthy();
});
Response:
● Home › Show Button to scan order QR Code
expect(received).toBeTruthy()
Received: null
44 | );
45 | //console.log(screen.debug(null, Infinity));
> 46 | expect(queryByTestId('qrCodeButton')).toBeTruthy();
| ^
47 | });
48 | });
49 |
at Object.toBeTruthy (src/screens/Home.test.js:46:43)