Skip to content

Interface mocks cannot be bound in inversify containers #222

@nseniak-iziwork

Description

@nseniak-iziwork

We use inversify for IOC (https://inversify.io/). Injecting mocks is an important testing use case for us. However, we found that interface mocks cannot be properly bound in inversify contexts.

Here's code combining inversify and ts-mockito that shows the problem:

import "reflect-metadata";
import { Container } from "inversify";
import { instance, mock } from "ts-mockito";

const container = new Container();

// Binding a class mock: works as expected
class Bar {}

const barMock = mock(Bar);
container.bind<Bar>("Bar").toConstantValue(instance(barMock));
const barMockGet = container.get<IFoo>("Bar"); // => barMock (expected)

// Binding an interface mock: doesn't work
interface IFoo {
  prop: string;
}

const ifooMock = mock<IFoo>();
container.bind<IFoo>("IFoo").toConstantValue(instance(ifooMock));
const ifooMockGet = container.get<IFoo>("IFoo"); // => null (should be ifooMock)

After looking into the inversify code, it seems that the problem is that inversify.isPromise incorrectly returns true for interface mocks, which makes invetsify try to resolve the mock, resulting in a null value:

import { isPromise } from "inversify/lib/utils/async";

const isBarMockPromise = isPromise(barMock); // => false (expected)
const isIfooMockPromise = isPromise(ifooMock); // => true (should be false)

The inversify code for isPromise is here: https://github.com/inversify/InversifyJS/blob/master/src/utils/async.ts

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions