{"id":15864,"library":"ts-mockery","title":"ts-mockery","description":"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.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/ike18t/ts-mockery","tags":["javascript","Mock","Testing","TypeScript","typescript"],"install":[{"cmd":"npm install ts-mockery","lang":"bash","label":"npm"},{"cmd":"yarn add ts-mockery","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-mockery","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for type checking, compilation, and leveraging the library's type-safe mocking features.","package":"typescript","optional":false}],"imports":[{"note":"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.","wrong":"const Mock = require('ts-mockery');","symbol":"Mock","correct":"import { Mock } from 'ts-mockery';"},{"note":"`Mock` is a named export, not a default export. `Mock.of` is the main method for creating type-safe partial mocks.","wrong":"import Mock from 'ts-mockery'; const myMock = Mock.of<MyInterface>({});","symbol":"Mock.of","correct":"import { Mock } from 'ts-mockery'; const myMock = Mock.of<MyInterface>({});"},{"note":"`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.","wrong":"import { noop } from 'ts-mockery';","symbol":"Mock.noop","correct":"import { Mock } from 'ts-mockery'; const func = Mock.noop;"}],"quickstart":{"code":"import { Mock } from 'ts-mockery';\n\ninterface UserService {\n  getUser(id: number): Promise<{ id: number; name: string; email?: string }>;\n  updateUser(user: { id: number; name: string }): void;\n  deleteUser(id: number): boolean;\n}\n\n// Create a type-safe partial mock for UserService\nconst userServiceMock = Mock.of<UserService>({\n  getUser: (id: number) => Promise.resolve({ id: id, name: 'Mocked User' }), // Only specify necessary properties\n  updateUser: Mock.noop, // Function is auto-spied and does nothing\n  deleteUser: () => true // Provide a simple return value\n});\n\nasync function runTest() {\n  // Use the mocked service in a test context\n  const userId = 123;\n  const userResult = await userServiceMock.getUser(userId);\n  console.log(`Retrieved user: ${userResult.name} (ID: ${userResult.id})`);\n  \n  userServiceMock.updateUser({ id: userId, name: 'Updated User' });\n  const deleteSuccess = userServiceMock.deleteUser(userId);\n\n  // Assertions (using Jest-like syntax for demonstration)\n  console.assert(userResult.id === userId, 'User ID should match');\n  console.assert(userServiceMock.updateUser.toHaveBeenCalled, 'updateUser should have been called');\n  console.assert(deleteSuccess === true, 'deleteUser should return true');\n  console.assert(userServiceMock.deleteUser.mock.calls[0][0] === userId, 'deleteUser should be called with correct ID');\n}\n\nrunTest();","lang":"typescript","description":"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."},"warnings":[{"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.","message":"ts-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.","severity":"breaking","affected_versions":">=2.0.0"},{"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)`.","message":"When 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"When 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"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.","cause":"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.","error":"TS2345: Argument of type '{ ... }' is not assignable to parameter of type 'RecursivePartial<T>'."},{"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`.","cause":"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.","error":"TypeError: (0, ts_mockery_1.Mock) is not a function"},{"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'); }`.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'toHaveBeenCalled')"}],"ecosystem":"npm"}