-
Notifications
You must be signed in to change notification settings - Fork 94
Open
Description
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
Labels
No labels