You should be able to do something like this.
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useGetData } from './api'; // RTK Query API
import MyComponent from './MyComponent';
jest.mock('./useGetData');
describe('MyComponent', () => {
beforeEach(() => {
useGetData.mockClear();
});
it('should render data after API request', async () => {
const mockData = {
id: 1,
name: 'John Doe',
email: '[email protected]'
};
useGetData.mockReturnValueOnce({
data: mockData,
isLoading: false,
isSuccess: true,
isError: false,
error: null,
});
render(<MyComponent />);
// Check that loading state is not displayed
expect(screen.queryByText('Loading...')).toBeNull();
// Check that data is displayed correctly
expect(screen.getByText('Name: John Doe')).toBeInTheDocument();
expect(screen.getByText('Email: [email protected]')).toBeInTheDocument();
});
});
In this example, we are testing that MyComponent
correctly displays data after a successful useGetData
hook call. We simulate the useGetData
hook by mocking it using jest.mock
and setting up a mock return value using useGetData.mockReturnValueOnce
. Then, we render the component and verify that the loading state is not displayed and that the data is correctly displayed using expect statements. It's worth noting that we don't need to wait for an API request to complete, as useGetData
already returns the data we wish to test.