ts-mock-imports provides an intuitive way to mock ES6 `import` dependencies for TypeScript classes during unit testing, without requiring explicit dependency injection. It is built on top of `sinon` for stubbing capabilities and leverages TypeScript's module resolution to intercept imported classes. The library is currently at version 1.3.19 and primarily sees minor patch releases, focusing on dependency updates and bug fixes rather than rapid feature additions, indicating a mature and stable codebase. A key differentiator is its direct manipulation of imported modules to replace original classes with type-safe stub versions, enabling seamless testing of code that directly instantiates its dependencies. It intercepts and replaces actual class constructors or functions exported via ES6 `import` statements with Sinon stubs at runtime, allowing fine-grained control over dependencies without modifying the source code under test. It requires both `sinon` (version >= 4.1.2) and `typescript` (version >= 2.6.1) as peer dependencies to function correctly.
npm install ts-mock-importsVerified import paths — ran on the pinned version, not inferred.
Demonstrates mocking a TypeScript class imported via ES6 syntax, replacing its constructor and methods with stubs to prevent execution of original logic and control return values.
Standardize module import paths across your project, often by using `tsconfig.json` `paths` aliases, or ensure relative paths are identical between consumer and test files.
For modules exhibiting this error, use `InPlaceMockManager` instead of `ImportMock.mockClass`. This manager is designed to work around the getter issue. Example: `const mockManager = new InPlaceMockManager(fooModule, 'Foo');`
Always include `ImportMock.restore()` in an `afterEach` or `afterAll` hook in your test setup to reset the module state.
Be aware that complex module bundlers (e.g., Webpack, Rollup) or newer Node.js ESM loading behaviors might introduce challenges. Consider alternative dependency injection patterns if encountering consistent issues, or ensure your testing environment aligns with the library's assumptions about module loading.
Ensure `npm install sinon typescript --save-dev` has been run in your project.
Replace `ImportMock.mockClass` with `new InPlaceMockManager(module, 'ClassName');` to use an alternative mocking strategy that bypasses the getter restriction.
Verify that `import * as myModule from './path/to/module';` in your test file uses the exact same relative or aliased path as the file that imports `ClassName` in your application code.
Install the required peer dependencies: `npm install sinon typescript --save-dev`.
Ensure the module you are trying to mock is indeed exporting a class via ES6 `export class MyClass { ... }` or `export default class MyClass { ... }` and is being consumed via `import` statements. The library is not compatible with `requirejs`.