// Async (for elements that appear later) await screen.findByText('Loaded')
import render, screen from '@testing-library/react' import UserProfile from './UserProfile' // Mock fetch globally global.fetch = jest.fn() React Testing Library and Jest- The Complete Guide
// Test error states render(<Component onError=mockError />) // Don't test internal state expect(component.state('isOpen')).toBe(true) // Don't use testid as default screen.getByTestId('submit-button') // Async (for elements that appear later) await screen
test('loads and displays user', async () => const mockUser = name: 'John Doe' fetch.mockResolvedValueOnce( json: async () => mockUser, ) Component onError=mockError />
// Test behavior, not implementation expect(screen.getByText('Welcome John')).toBeInTheDocument()
expect(result.current.count).toBe(1) ) Mock functions with Jest const mockFn = jest.fn() mockFn('hello') expect(mockFn).toHaveBeenCalledWith('hello') expect(mockFn).toHaveBeenCalledTimes(1) // Mock return value jest.fn().mockReturnValue('fixed value') jest.fn().mockResolvedValue('async value') jest.fn().mockImplementation(arg => arg * 2) Mock modules // Mock entire module jest.mock('../api', () => ( fetchUser: jest.fn(), )) // Mock with dynamic implementation jest.mock('axios', () => ( get: jest.fn(() => Promise.resolve( data: id: 1 )), )) Mock timers jest.useFakeTimers() test('delayed action', () => render(<DelayedComponent />)