Skip to content

Commit

Permalink
fix(di): reimplement imports option correctly on DITest.create()
Browse files Browse the repository at this point in the history
Closes: #2660
  • Loading branch information
Romakita committed May 8, 2024
1 parent ecc3d30 commit 785c186
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
3 changes: 2 additions & 1 deletion packages/di/src/common/services/InjectorService.ts
Expand Up @@ -293,7 +293,8 @@ export class InjectorService extends Container {

// allow mocking or changing provider instance before loading injector
this.settings.imports = this.settings.imports
?.map((meta) => {
?.filter((meta) => meta.token !== InjectorService)
.map((meta) => {
if ("token" in meta && "use" in meta) {
const {token, use} = meta;
const provider = this.getProvider(token);
Expand Down
63 changes: 63 additions & 0 deletions packages/di/src/node/services/DITest.spec.ts
@@ -0,0 +1,63 @@
import {Inject, Injectable, InjectorService, registerProvider} from "../../index";
import {DITest} from "../services/DITest";

@Injectable()
export class MyService {
@Inject("TOKEN")
token: any;
}

registerProvider({
provide: "TOKEN",
useFactory() {
return {token: "token"};
}
});
describe("DITest", () => {
describe("create()", () => {
beforeEach(() =>
DITest.create({
imports: [
{
token: "TOKEN",
use: {token: "test"}
},
{
token: InjectorService, // not possible to override the injector
use: "test"
}
]
})
);
afterEach(() => DITest.reset());

it("should return a service with pre mocked dependencies", () => {
const service = DITest.get<MyService>(MyService);

expect(service.token).toEqual({
token: "test"
});
});

it("should return a service with pre mocked dependencies (invoke)", async () => {
const service = await DITest.invoke<MyService>(MyService);

expect(service.token).toEqual({
token: "test"
});
});

it("should return a service with pre mocked dependencies (invoke + mock)", async () => {
const service = await DITest.invoke<MyService>(MyService, [
{
token: "TOKEN",
use: {token: "test2"}
}
]);

expect(service.token).toEqual({
token: "test2"
});
});
});
});
2 changes: 1 addition & 1 deletion packages/di/src/node/services/DITest.ts
@@ -1,6 +1,6 @@
import {Env, getValue, isClass, isPromise, setValue} from "@tsed/core";
import {$log} from "@tsed/logger";
import {createContainer, InjectorService, LocalsContainer, OnInit, TokenProvider, TokenProviderOpts} from "../../common/index";
import {createContainer, InjectorService, LocalsContainer, OnInit, Provider, TokenProvider, TokenProviderOpts} from "../../common/index";
import {DIContext} from "../domain/DIContext";
import {setLoggerConfiguration} from "../utils/setLoggerConfiguration";

Expand Down

0 comments on commit 785c186

Please sign in to comment.