
ReactJS
Learn to test async code in Jest.
test('displays user after loading', async () => {
render(<UserProfile userId={1} />);
const name = await screen.findByText('Alice');
expect(name).toBeInTheDocument();
});test('fetches and displays data', async () => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ name: 'Alice' })
})
);
render(<UserProfile userId={1} />);
const name = await screen.findByText('Alice');
expect(name).toBeInTheDocument();
});test('handles async operations', async () => {
render(<DataLoader />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
const data = await screen.findByText('Data loaded');
expect(data).toBeInTheDocument();
});test('displays error on failure', async () => {
global.fetch = jest.fn(() =>
Promise.reject(new Error('Network error'))
);
render(<UserProfile userId={1} />);
const error = await screen.findByText('Network error');
expect(error).toBeInTheDocument();
});Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep โข Build Real โข Verify Skills โข Launch Forward