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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Mocking & Spying in Jest | TypeScript Mastery lesson | BraveProgrammer
  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 39 of 56

·Typescript

Mocking & Spying in Jest

15 minutes

Course progress70%

Jest Mock Functions

const mockFn = jest.fn((x: number) => x * 2);
mockFn(2);
expect(mockFn).toHaveBeenCalledWith();
(mockFn).();
2
expect
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).
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from TypeScript MasteryBrowse activities
Previous lessonTesting with Jest & `ts-jest`Continue to lesson 40Linting & Formatting – ESLint, Prettier, and `eslint-plugin-typescript`Back to TypeScript Mastery curriculum