Typescript Mock Imports

1.3.19 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { ImportMock } from 'ts-mock-imports';
import { Bar } from '../src/bar';
import * as fooModule from '../src/foo';

// Imagine 'Foo' class in '../src/foo.ts' has a constructor that throws an error
// and 'Bar' in '../src/bar.ts' instantiates 'Foo'.

describe('Bar', () => {
  let mockFooManager: ImportMock.MockManager<any>;

  beforeEach(() => {
    // Mock the 'Foo' class from 'fooModule'
    // This intercepts any 'new Foo()' call within modules that imported fooModule
    mockFooManager = ImportMock.mockClass(fooModule, 'Foo');
  });

  afterEach(() => {
    // Restore all mocks to their original implementations to ensure test isolation
    ImportMock.restore();
  });

  it('should create an instance of Bar without error when Foo is mocked', () => {
    // Now, new Bar() will use the mocked Foo, preventing the error
    const bar = new Bar();
    expect(bar).toBeInstanceOf(Bar);
  });

  it('should allow stubbing methods of the mocked Foo class', () => {
    // Configure a mock response for the 'getCount' method of Foo
    mockFooManager.mock('getCount', () => 42);

    // If Bar were to call getCount internally, it would now return 42
    // For demonstration, let's assume Bar had a method that called Foo.getCount()
    // (This example focuses on the core mocking setup)
    // const bar = new Bar();
    // const result = bar.getFooCount(); // Assuming such a method exists
    // expect(result).toBe(42);
    
    const mockFooInstance = mockFooManager.get;// For a real test, you'd test Bar's interaction with Foo
  });
});

view raw JSON →