{"id":12183,"library":"ts-mockito","title":"ts-mockito","description":"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.","status":"active","version":"2.6.1","language":"javascript","source_language":"en","source_url":"https://github.com/NagRock/ts-mockito","tags":["javascript","mock","typescript","tests","fake","stub","spy"],"install":[{"cmd":"npm install ts-mockito","lang":"bash","label":"npm"},{"cmd":"yarn add ts-mockito","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-mockito","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"CommonJS require() syntax is outdated for modern TypeScript projects; use ES Module imports.","wrong":"const { mock } = require('ts-mockito');","symbol":"mock","correct":"import { mock } from 'ts-mockito';"},{"note":"This is a named export, not the default export. Importing as default is incorrect.","wrong":"import instance from 'ts-mockito';","symbol":"instance","correct":"import { instance } from 'ts-mockito';"},{"note":"Prefer named ES Module imports over CommonJS destructuring for better static analysis and tree-shaking.","wrong":"const when = require('ts-mockito').when;","symbol":"when","correct":"import { when } from 'ts-mockito';"},{"note":"The function name is `verify` (lowercase), not `Verify`.","wrong":"import { Verify } from 'ts-mockito';","symbol":"verify","correct":"import { verify } from 'ts-mockito';"},{"note":"Commonly used matcher. Type checking was improved in v2.5.0, potentially causing new compilation errors.","symbol":"deepEqual","correct":"import { deepEqual } from 'ts-mockito';"}],"quickstart":{"code":"import { mock, instance, when, verify, anyNumber } from 'ts-mockito';\n\nclass FooService {\n  getBar(value: number): string {\n    throw new Error('Should not be called directly');\n  }\n  async getAsyncData(id: string): Promise<string> {\n    return Promise.resolve(`Data for ${id}`);\n  }\n  get sampleGetter(): string {\n    return 'realValue';\n  }\n}\n\n// Create a mock instance of FooService\nconst mockedFooService: FooService = mock(FooService);\n\n// Stub a method call to return a specific value\nwhen(mockedFooService.getBar(3)).thenReturn('three');\nwhen(mockedFooService.getBar(anyNumber())).thenReturn('anyNumberResult');\n\n// Stub a getter property\nwhen(mockedFooService.sampleGetter).thenReturn('mockedGetterValue');\n\n// Stub an async method to resolve a promise\nwhen(mockedFooService.getAsyncData('testId')).thenResolve('resolvedData');\n\n// Get the mock instance to use in your code\nconst fooService: FooService = instance(mockedFooService);\n\n// Use the mocked instance\nconsole.log('Call with 3:', fooService.getBar(3)); // Should print 'three'\nconsole.log('Call with 5:', fooService.getBar(5)); // Should print 'anyNumberResult'\nconsole.log('Getter value:', fooService.sampleGetter); // Should print 'mockedGetterValue'\nfooService.getAsyncData('testId').then(data => {\n  console.log('Async data:', data); // Should print 'resolvedData'\n});\n\n// Verify that methods were called as expected\nverify(mockedFooService.getBar(3)).once();\nverify(mockedFooService.getBar(anyNumber())).thrice(); // 3, 5, and the `anyNumber()` for the `5` call\nverify(mockedFooService.getAsyncData('testId')).called();\n// Optionally, verify that an unexpected call was NOT made (e.g., if you only stubbed 'testId')\n// verify(mockedFooService.getAsyncData('otherId')).never();\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Review `deepEqual` usages. If compilation errors occur, consider using `Partial<ExpectedType>` for the expected argument, e.g., `deepEqual(expectedParams as Partial<Foo>)`.","message":"The `deepEqual` matcher received significant type checking improvements in v2.5.0. This can cause existing code to fail compilation if provided arguments do not perfectly match the expected type, for example, if the expected parameter has more fields than the provided one. Use `Partial<T>` for easy migration if you intend to ignore extra fields.","severity":"breaking","affected_versions":">=2.5.0"},{"fix":"Refer to the '1.x to 2.x migration guide' linked in the project's README on GitHub.","message":"Upgrading from ts-mockito 1.x to 2.x involves significant changes in API usage. Consult the official 1.x to 2.x migration guide on GitHub to understand the required updates for your codebase.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure your runtime environment supports ES6 Proxy objects. For older environments, consider refactoring properties to use explicit getter methods.","message":"Stubbing property values that do not have explicit getters (i.e., just direct properties) only works correctly in environments that support Proxy objects (ES6 and later). In older JavaScript environments without Proxy support, this feature will not function as expected.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When mocking an interface, use `mock<InterfaceName>()` syntax. Do not pass the interface name as a direct argument to `mock()`.","message":"Support for mocking interfaces was introduced in v2.4.0. To mock an interface, you must use a generic type with the `mock` function and omit its argument: `let mockedInterface: MyInterface = mock<MyInterface>();` Incorrect syntax will lead to runtime errors or compilation issues.","severity":"gotcha","affected_versions":">=2.4.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"This issue was fixed in v2.2.9. Ensure you are using ts-mockito version 2.2.9 or newer.","cause":"Specific scenarios involving deeply nested calls or complex mocking setups could trigger a stack overflow in earlier versions.","error":"Maximum call stack size exceeded"},{"fix":"Cast the expected argument to `Partial<YourType>` or `any` if a partial match is intended, e.g., `verify(mockedService.method(deepEqual(expectedParams as Partial<ServiceType>))).called();`","cause":"A common type error when using the `deepEqual` matcher after v2.5.0 if the expected value's type does not perfectly align with the actual argument's type, especially when the expected type has more required fields.","error":"Type 'Foo' is not assignable to type 'Partial<Foo>'. Property 'bar' is missing in type 'Partial<Foo>' but required in type 'Foo'."},{"fix":"Review your test logic to ensure the mock method is being called the expected number of times or adjust your `verify` expectation (e.g., `once()`, `twice()`, `times(count)`, `atLeast(count)`).","cause":"This is a runtime error from ts-mockito's `verify` function indicating a mismatch between the expected number of calls for a specific method/argument combination and the actual calls made to the mock.","error":"Error: Expected \"methodName(arg)\" to be called X time(s). But has been called Y time(s)."},{"fix":"Always ensure you call `instance(mockedObject)` to get the actual mocked object to interact with. Double-check that `mock()` is receiving a valid class or abstract class.","cause":"Can occur if `instance()` is not called to retrieve the mockable object before passing it to the code under test, or if the `mock()` function is passed an invalid argument.","error":"TypeError: Cannot read properties of undefined (reading '__ts_mockito_args')"}],"ecosystem":"npm"}