ts-mockito for TypeScript: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

ts-mockito for TypeScript: Complete Guide with Examples

1. What Is ts-mockito and Why Use It

ts-mockito is a powerful library for creating mocks, stubs, and spies in TypeScript. Inspired by the popular Java library Mockito, it provides a familiar API for developers transitioning from Java or Python. The main goal of ts-mockito is to simplify unit testing by isolating the code under test from external dependencies: databases, HTTP clients, file systems, and other services.

Why is this necessary? In modern TypeScript applications, classes and functions often depend on other components. Without mocks, testing these connections turns into integration testing that requires environment setup. ts-mockito lets you create "fake" objects with predefined behavior, and verify which methods were called and with what arguments. This makes tests fast, deterministic, and easy to maintain.

The library supports all core Mockito features: creating mocks via mock(), configuring behavior with when() and thenReturn(), verifying calls with verify(), and working with spies via spy(). ts-mockito is fully typed and integrates seamlessly with popular testing frameworks like Jest, Mocha, and Jasmine.

2. Installation

Install ts-mockito via npm (Node Package Manager). Run the following command in your project root:

npm install ts-mockito --save-dev

If you're using yarn:

yarn add ts-mockito --dev

The library has no mandatory dependencies beyond TypeScript itself (version 4.0+). After installation, import the necessary functions in your test files:

import { mock, when, verify, instance, anything, anyOfClass, deepEqual, spy } from 'ts-mockito';

Note: ts-mockito uses proxy objects to intercept calls. This means you always work with "wrapped" objects, not real class instances.

3. Quick Start — Minimal Working Example

Let's look at a simple example: we have a UserService class that depends on UserRepository. We want to test the getUser method without hitting a real database.

// user-repository.ts
export class UserRepository {
    async findById(id: number): Promise<{ id: number; name: string } | null> {
        // Real database query
        return null;
    }
}

// user-service.ts
export class UserService {
    constructor(private repository: UserRepository) {}

    async getUser(id: number): Promise<string> {
        const user = await this.repository.findById(id);
        if (!user) {
            throw new Error('User not found');
        }
        return `User: ${user.name}`;
    }
}

// user-service.spec.ts
import { mock, when, instance, verify, anything } from 'ts-mockito';
import { UserService } from './user-service';
import { UserRepository } from './user-repository';

describe('UserService', () => {
    it('should return user name when user exists', async () => {
        // 1. Create a mock of the repository
        const mockRepository: UserRepository = mock(UserRepository);
        
        // 2. Configure behavior: when findById(1) is called, return an object
        when(mockRepository.findById(1)).thenResolve({ id: 1, name: 'Alice' });
        
        // 3. Get the real mock instance
        const repositoryInstance = i                    

Recommendations