I want to test my component in Jest and that it is displaying fetched data correctly. I have the following component, which has a useEffect
hook that calls a function called getData
. getData
fetches to the back end API, converts the response to json
, and returns the json
to the component. The data is then updated in state and displayed on screen. The returned data is a very simple array that looks like: [{ title: "test", id: 1 }, ...]
.
import React, { useEffect, useState } from "react";
import { FlatList, Text, View } from "react-native";
import { getData } from "./getData"; // <- returns an array
const MyComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
(async() => {
const returnedArray = await getData(); // <- returns an array
setData(returnedArray);
})();
}, []);
return (
<View>
<FlatList
data={ data }
renderItem={item => <Text>{item.title}</Text>}
keyExtractor={item => item.id}
/>
</View>
);
};
I want to run the following test, trying to mock the fetch call within global.fetch
.
import * as React from 'react';
import { render, act } from '@testing-library/react-native';
import MyComponent from './MyComponent';
global.fetch = jest.fn(() => Promise.resolve({
title: "test",
id: 1
}));
describe('Testing react native', () => {
it('displays data from useEffect hook', async () => {
const { getByText } = await act(async () => render(<MyComponent />));
const title = getByText("test");
expect(title).toBeTruthy();
});
}
This test is failing with the following error:
Can't access .root on unmounted test renderer
Can someone help me understand the proper way to test a Component that fetches data from a useEffect
hook in Jest
? Thanks.