ts-mockito

2.6.1 · active · verified Sun Apr 19

ts-mockito is a comprehensive mocking library for TypeScript, drawing inspiration from the well-known Java Mockito.org framework. Currently stable at version 2.6.1, it provides strongly typed mocks that enhance unit testing with features such as automatic IDE autocompletion and clear, readable error messages. The library allows for mocking classes, abstract classes, and interfaces, spying on real objects, and offers extensive stubbing capabilities including returning values, throwing errors, resolving/rejecting promises, and executing custom functions. ts-mockito maintains a moderate release cadence, with several updates annually focusing on new features and bug fixes. Its key differentiators include robust TypeScript integration, advanced verification options like call count, order, and argument capturing, and recent enhancements like improved type checking for the `deepEqual` matcher and multi-mock resetting.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic ts-mockito usage: creating a mock, stubbing method calls and getters, handling async operations, and verifying method invocations with specific arguments and call counts.

import { mock, instance, when, verify, anyNumber } from 'ts-mockito';

class FooService {
  getBar(value: number): string {
    throw new Error('Should not be called directly');
  }
  async getAsyncData(id: string): Promise<string> {
    return Promise.resolve(`Data for ${id}`);
  }
  get sampleGetter(): string {
    return 'realValue';
  }
}

// Create a mock instance of FooService
const mockedFooService: FooService = mock(FooService);

// Stub a method call to return a specific value
when(mockedFooService.getBar(3)).thenReturn('three');
when(mockedFooService.getBar(anyNumber())).thenReturn('anyNumberResult');

// Stub a getter property
when(mockedFooService.sampleGetter).thenReturn('mockedGetterValue');

// Stub an async method to resolve a promise
when(mockedFooService.getAsyncData('testId')).thenResolve('resolvedData');

// Get the mock instance to use in your code
const fooService: FooService = instance(mockedFooService);

// Use the mocked instance
console.log('Call with 3:', fooService.getBar(3)); // Should print 'three'
console.log('Call with 5:', fooService.getBar(5)); // Should print 'anyNumberResult'
console.log('Getter value:', fooService.sampleGetter); // Should print 'mockedGetterValue'
fooService.getAsyncData('testId').then(data => {
  console.log('Async data:', data); // Should print 'resolvedData'
});

// Verify that methods were called as expected
verify(mockedFooService.getBar(3)).once();
verify(mockedFooService.getBar(anyNumber())).thrice(); // 3, 5, and the `anyNumber()` for the `5` call
verify(mockedFooService.getAsyncData('testId')).called();
// Optionally, verify that an unexpected call was NOT made (e.g., if you only stubbed 'testId')
// verify(mockedFooService.getAsyncData('otherId')).never();

view raw JSON →