ts-mockery

2.0.0 · active · verified Tue Apr 21

ts-mockery is a TypeScript mocking library designed for creating type-safe and intuitive mocks for unit testing. Currently at version 2.0.0, it provides a comprehensive suite of features including full IntelliSense support, deep nested object mocking, and automatic spy setup for functions. The library integrates seamlessly with popular testing frameworks such as Jest and Jasmine, offering a consistent API across different test runners. Its key differentiators include a strong emphasis on compile-time type safety through partial object mocking with `RecursivePartial<T>`, robust Promise handling, and advanced capabilities for mocking static methods and imported modules. While a specific release cadence isn't explicitly documented, its major versioning indicates active development and a commitment to modern TypeScript practices, requiring TypeScript 4.5 or newer.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating a type-safe partial mock for a `UserService` interface, setting up a Promise-resolving method, an auto-spied no-op function, and a boolean-returning function, then asserting method calls and arguments.

import { Mock } from 'ts-mockery';

interface UserService {
  getUser(id: number): Promise<{ id: number; name: string; email?: string }>;
  updateUser(user: { id: number; name: string }): void;
  deleteUser(id: number): boolean;
}

// Create a type-safe partial mock for UserService
const userServiceMock = Mock.of<UserService>({
  getUser: (id: number) => Promise.resolve({ id: id, name: 'Mocked User' }), // Only specify necessary properties
  updateUser: Mock.noop, // Function is auto-spied and does nothing
  deleteUser: () => true // Provide a simple return value
});

async function runTest() {
  // Use the mocked service in a test context
  const userId = 123;
  const userResult = await userServiceMock.getUser(userId);
  console.log(`Retrieved user: ${userResult.name} (ID: ${userResult.id})`);
  
  userServiceMock.updateUser({ id: userId, name: 'Updated User' });
  const deleteSuccess = userServiceMock.deleteUser(userId);

  // Assertions (using Jest-like syntax for demonstration)
  console.assert(userResult.id === userId, 'User ID should match');
  console.assert(userServiceMock.updateUser.toHaveBeenCalled, 'updateUser should have been called');
  console.assert(deleteSuccess === true, 'deleteUser should return true');
  console.assert(userServiceMock.deleteUser.mock.calls[0][0] === userId, 'deleteUser should be called with correct ID');
}

runTest();

view raw JSON →