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-mockeryVerified import paths — ran on the pinned version, not inferred.
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.
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.
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)`.
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.
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.
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`.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'); }`.