Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
๐Ÿงช Testing Basics๐ŸŽจ Rendering Components๐Ÿ” Querying Elements๐Ÿ‘† Simulating Events๐Ÿงช Async Testing๐ŸŽญ Mocking๐Ÿงช Test Organization๐Ÿงช Testing Best Practices
Reactjs/Testing/Mocking

๐ŸŽญ Mocking with Jest

Learn to mock dependencies in tests.

Mock Functions

test('calls callback', () => {
  const handleClick = jest.fn();
  render(<Button onClick={handleClick} />);
  
  userEvent.click(screen.getByRole('button'));
  
  expect(handleClick).toHaveBeenCalled();
});

Tracking Calls

test('tracks function calls', () => {
  const mockFn = jest.fn();
  
  mockFn(1);
  mockFn(2);
  
  expect(mockFn).toHaveBeenCalledTimes(2);
  expect(mockFn).toHaveBeenCalledWith(1);
  expect(mockFn).toHaveBeenLastCalledWith(2);
});

Mock Return Values

test('uses mock return value', () => {
  const mockFn = jest.fn().mockReturnValue(42);
  expect(mockFn()).toBe(42);
});

Mocking Modules

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();
});

Mocking Timers

test('calls callback after delay', () => {
  jest.useFakeTimers();
  const callback = jest.fn();
  
  setTimeout(callback, 1000);
  jest.runAllTimers();
  
  expect(callback).toHaveBeenCalled();
});

โœ… Key Takeaways

  • Use **jest.fn()** to create mock functions
  • Track **calls** and **arguments**
  • Use **mockReturnValue()** for return values
  • Mock **modules** with **jest.mock()**
  • Use **jest.useFakeTimers()** for timing

Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn