To write Jest test cases for this Expo React Native app, we need to create test files that contains various tests to verify the behavior of the HomeScreen component. We will mock certain external dependencies like network requests and other hooks to isolate the component's behaviors.
Here is a basic set of Jest tests:
Set up Jest and React Native Testing Library.
Mock external dependencies.
Write test cases to:
Render the component correctly.
Handle the search functionality.
Verify infinite scroll loading.
Verify sharing functionality.
1. Setup Dependencies
Make sure you have the necessary dependencies installed:
sh Copy code
npm install --save-dev jest @testing-library/react-native @babel/preset-react-native react-test-renderer
npm install --save-dev jest-expo
Add the following Jest configuration to your package.json:
json Copy code
"jest": {
"preset": "jest-expo",
"setupFilesAfterEnv": ["@testing-library/jest-native/extend-expect"],
"transformIgnorePatterns": [
"node_modules/(?!@react-native|react-native|@react-navigation)"
]
}
2. Mock External Dependencies
Create a new file __mocks__/fetchGifs.js to mock the fetchGifs function from @/utils/giphy.
js Copy code
// __mocks__/fetchGifs.js
export const fetchGifs = jest.fn().mockResolvedValue([
{
id: '1',
images: {
fixed_height: { url: 'http://example.com/gif1.gif' },
},
},
{
id: '2',
images: {
fixed_height: { url: 'http://example.com/gif2.gif' },
},
},
{
id: '3',
images: {
fixed_height: { url: 'http://example.com/gif3.gif' },
},
},
]);
Create another mock for the hook useFavoriteGifs to avoid actual storage operations:
js Copy code
// __mocks__/useFavoriteGifs.js
export const useFavoriteGifs = () => ({
addFavorite: jest.fn(),
});
3. Write the Test Cases
Now, create a test file HomeScreen.test.js and write the test cases.
js Copy code
// HomeScreen.test.js
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react-native';
import HomeScreen from '@/HomeScreen';
import { fetchGifs } from '@/utils/giphy';
import { useFavoriteGifs } from '@/hooks/useFavoriteGifs';
jest.mock('@/utils/giphy');
jest.mock('@/hooks/useFavoriteGifs');
describe('HomeScreen', () => {
it('renders correctly', () => {
const { getByText, getByPlaceholderText } = render(<HomeScreen />);
expect(getByText('Search GIPHY')).toBeTruthy();
expect(getByPlaceholderText('Search...')).toBeTruthy();
});
it('searches for GIFs and displays them', async () => {
const { getByPlaceholderText, getByText, getAllByTestId } = render(<HomeScreen />);
const searchInput = getByPlaceholderText('Search...');
fireEvent.changeText(searchInput, 'hello');
fireEvent(searchInput, 'submitEditing');
await waitFor(() => {
expect(fetchGifs).toHaveBeenCalledWith('hello');
expect(getAllByTestId('gif')).toHaveLength(3);
});
});
it('loads more GIFs when scrolling to the end', async () => {
const { getByPlaceholderText, getAllByTestId, getByTestId } = render(<HomeScreen />);
// Initial search
fireEvent.changeText(getByPlaceholderText('Search...'), 'hello');
fireEvent(getByPlaceholderText('Search...'), 'submitEditing');
await waitFor(() => expect(fetchGifs).toHaveBeenCalledTimes(1));
// Trigger infinite scroll
fireEvent.scroll(getByTestId('flatlist'), {
nativeEvent: {
contentOffset: { y: 100 },
contentSize: { height: 1000, width: 100 },
layoutMeasurement: { height: 100, width: 100 },
},
});
await waitFor(() => {
expect(fetchGifs).toHaveBeenCalledTimes(2);
expect(getAllByTestId('gif')).toHaveLength(6); // 3 initial + 3 more
});
});
it('shares a GIF when long pressed', async () => {
const { getByPlaceholderText, getAllByTestId } = render(<HomeScreen />);
const searchInput = getByPlaceholderText('Search...');
fireEvent.changeText(searchInput, 'hello');
fireEvent(searchInput, 'submitEditing');
await waitFor(() => {
expect(fetchGifs).toHaveBeenCalled();
});
const gif1 = getAllByTestId('gif')[0];
jest.spyOn(global.navigator, 'share').mockResolvedValue({});
fireEvent(gif1, 'longPress');
await waitFor(() => {
expect(global.navigator.share).toHaveBeenCalledWith({
message: 'Check out this GIF: http://example.com/gif1.gif',
});
});
});
});
4. Adjust HomeScreen
To ensure consistency and make testing easier, modify the HomeScreen slightly to include testID props for each GIF and FlatList.
js Copy code
<FlatList
data={gifs}
keyExtractor={(item) => item.id}
testID="flatlist"
renderItem={({ item }) => (
<TouchableOpacity onLongPress={() => handleLongPress(item.images.fixed_height.url)} onPress={() => addFavorite(item.id)}>
<Image source={{ uri: item.images.fixed_height.url }} style={styles.gif} testID="gif" />
</TouchableOpacity>
)}
onEndReached={loadMoreGifs}
onEndReachedThreshold={0.5}
ListFooterComponent={loading && <ActivityIndicator size="large" color="#0000ff" />}
/>
With these tests, you should be able to verify that your HomeScreen component behaves as expected under various conditions.