From 21dcec70191c92644302c64c01d558f005351dd2 Mon Sep 17 00:00:00 2001 From: Andrew Thigpen Date: Fri, 13 Sep 2024 14:11:20 -0400 Subject: [PATCH] fix(di): resolve LazyInject returning undefined --- .../src/common/decorators/lazyInject.spec.ts | 24 +++++++++++++++++++ .../di/src/common/decorators/lazyInject.ts | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/di/src/common/decorators/lazyInject.spec.ts b/packages/di/src/common/decorators/lazyInject.spec.ts index 63efc7cb1e2..f0fba4356a1 100644 --- a/packages/di/src/common/decorators/lazyInject.spec.ts +++ b/packages/di/src/common/decorators/lazyInject.spec.ts @@ -65,4 +65,28 @@ describe("LazyInject", () => { expect(lazyService).toEqual({}); }); + + it("should not return undefined if the package is imported but the bean has not been assigned yet", async () => { + @Injectable() + class MyInjectable { + @LazyInject("MyLazyModule", () => import("./__mock__/lazy.import.module")) + lazy: Promise; + } + + const injector = new InjectorService(); + const service = await injector.invoke(MyInjectable); + const originalLazyInvoke = injector.lazyInvoke.bind(injector); + const promise1 = service.lazy; + let promise2: Promise | undefined; + vi.spyOn(injector, "lazyInvoke").mockImplementationOnce((token) => { + promise2 = service.lazy; + return originalLazyInvoke(token); + }); + + const lazyService1 = await promise1; + const lazyService2 = await promise2; + + expect(lazyService1).not.toBeUndefined(); + expect(lazyService2).not.toBeUndefined(); + }); }); diff --git a/packages/di/src/common/decorators/lazyInject.ts b/packages/di/src/common/decorators/lazyInject.ts index fe768abad50..69459dd3a0f 100644 --- a/packages/di/src/common/decorators/lazyInject.ts +++ b/packages/di/src/common/decorators/lazyInject.ts @@ -31,7 +31,7 @@ export function LazyInject( injectProperty(target, propertyKey, { resolver(injector) { return async () => { - if (!token) { + if (!token || !bean) { const exports = await importPackage(packageName, resolver, optional); token = exports[key];