Registry / testing / ts-mockery

ts-mockery

JSON →
library2.0.0jsnpmunverified

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.

npm install ts-mockery
INSTALL
IMPORT
SIG · TS-MOCKERY
T
ts-mockery
testingjavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Mock
import { Mock } from 'ts-mockery';
const Mock = require('ts-mockery');
The primary entry point for creating mocks. `ts-mockery` is primarily designed for ESM environments with TypeScript, though CommonJS usage may work with proper transpilation.
Mock.of
import { Mock } from 'ts-mockery'; const myMock = Mock.of<MyInterface>({});
import Mock from 'ts-mockery'; const myMock = Mock.of<MyInterface>({});
`Mock` is a named export, not a default export. `Mock.of` is the main method for creating type-safe partial mocks.
Mock.noop
import { Mock } from 'ts-mockery'; const func = Mock.noop;
import { noop } from 'ts-mockery';
`Mock.noop` is a static property of the `Mock` class, commonly used to create auto-spied no-operation functions for methods that don't need a specific return value but whose calls need to be tracked.

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();
Debug
Known issues
breakingts-mockery version 2.0.0 requires TypeScript 4.5 or higher. Attempting to use it with older TypeScript versions will result in compilation errors due to incompatible type definitions and language features.
fix
Upgrade your project's TypeScript dependency to 4.5.0 or newer (e.g., `npm install typescript@^4.5 --save-dev`). Ensure your `tsconfig.json` targets a compatible `ESNext` module system if encountering import issues.
affects: >=2.0.0
gotchaWhen mocking imported modules or static methods, `ts-mockery` recommends specific import syntax to ensure type safety and proper mocking behavior. Using default exports or different import patterns might lead to issues.
fix
For module mocking, consider using `import * as Module from './module'` syntax. Ensure the module is not tree-shaken by your bundler. Static method mocking uses `Mock.staticMethod<T, K>(object: T, key: K, stub: Function)`.
affects: >=1.0.0
gotchaWhen creating partial mocks, properties not explicitly defined in the `Mock.of` object will be `undefined` by default (if optional) or may result in type errors if they are required properties of the mocked interface. TypeScript's strictness can flag these.
fix
Ensure all required properties of the interface are provided in your `Mock.of` call. For optional properties, explicitly set them to `undefined` or provide a default value if needed by the test logic. Leverage `RecursivePartial<T>` for deep partial mocks.
affects: >=1.0.0
Errors
Common errors & fixes
TS2345: Argument of type '{ ... }' is not assignable to parameter of type 'RecursivePartial<T>'.
The mock object provided to `Mock.of<T>` does not fully satisfy the `T` interface or contains properties with incompatible types. This often happens with required properties that are omitted or incorrectly typed.
fix
Review the interface `T` and ensure that all required properties are present in the mock object with correct types. For nested objects, ensure their types also align. The error message usually points to the specific incompatible property.
TypeError: (0, ts_mockery_1.Mock) is not a function
This error typically occurs when `ts-mockery` is imported using CommonJS `require()` syntax in a project configured for ESM, or if the bundler/runtime doesn't correctly resolve the module's exports. It indicates `Mock` is not correctly recognized as a callable constructor or object.
fix
Use ESM `import { Mock } from 'ts-mockery';` syntax. Ensure your `tsconfig.json` and build tools (like Webpack, Rollup, Jest) are configured for ESM (`"module": "ESNext"` or `"module": "Node16"`). If using Jest, ensure it runs in an ESM context or transpiles `node_modules`.
TypeError: Cannot read properties of undefined (reading 'toHaveBeenCalled')
This error usually occurs when attempting to assert `toHaveBeenCalled` on a mocked function that was not correctly set up as a spy. `ts-mockery` auto-spies functions when `Mock.noop` is used, or when a function stub is provided, but plain `undefined` or non-function values won't have the spy properties.
fix
Ensure the mocked function is explicitly assigned `Mock.noop` or a stub function (e.g., `() => { /* ... */ }`) within your `Mock.of` definition. For example: `myMethod: Mock.noop` or `myMethod: () => { console.log('Mocked method called'); }`.
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies
typescriptrequiredRequired for type checking, compilation, and leveraging the library's type-safe mocking features.
Agent activity
7 hits · last 30 days
node
6
Amazon
1
Resources
ts-mockery — npm install ts-mockery · libregistry