
ReactJS
Learn to mock dependencies in tests.
test('calls callback', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick} />);
userEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalled();
});test('tracks function calls', () => {
const mockFn = jest.fn();
mockFn(1);
mockFn(2);
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveBeenCalledWith(1);
expect(mockFn).toHaveBeenLastCalledWith(2);
});test('uses mock return value', () => {
const mockFn = jest.fn().mockReturnValue(42);
expect(mockFn()).toBe(42);
});jest.mock('./api');
import { fetchUser } from './api';
test('uses mocked API', async () => {
fetchUser.mockResolvedValue({ id: 1, name: 'Alice' });
render(<UserProfile userId={1} />);
const name = await screen.findByText('Alice');
expect(name).toBeInTheDocument();
});test('calls callback after delay', () => {
jest.useFakeTimers();
const callback = jest.fn();
setTimeout(callback, 1000);
jest.runAllTimers();
expect(callback).toHaveBeenCalled();
});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