Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 39 of 56 · Typescript

Mocking & Spying in Jest

Duration: 15 minutes

Jest Mock Functions

const mockFn = jest.fn((x: number) => x * 2);
mockFn(2);
expect(mockFn).toHaveBeenCalledWith(2);
expect(mockFn).toHaveReturnedWith(4);

Manual Mock Implementation

jest.spyOn(Math, 'random').mockReturnValue(0.5);
expect(Math.random()).toBe(0.5);

Auto‑mocking a module

jest.mock('../src/api'); // creates a mock based on the module’s shape
import { fetchUser } from '../src/api';
(fetchUser as jest.Mock).mockResolvedValue({ id: 1, name: 'Bob' });

Resetting mocks

afterEach(() => {
  jest.clearAllMocks();
});

Info

When testing TypeScript code, ensure the mock’s type matches the original (use as jest.Mock).

Previous: Testing with Jest & `ts-jest`Next: Linting & Formatting – ESLint, Prettier, and `eslint-plugin-typescript`