diff --git a/packages/ioc/package.json b/packages/ioc/package.json index c0f40f4..3cb32bf 100644 --- a/packages/ioc/package.json +++ b/packages/ioc/package.json @@ -4,7 +4,7 @@ "description": "Dependency Injection system", "main": "dist/index.js", "scripts": { - "test": "vitest --run", + "test": "vitest --watch", "tdd": "vitest", "build": "tsc" }, diff --git a/packages/ioc/src/container.ts b/packages/ioc/src/container.ts index d9b612c..18a26f5 100644 --- a/packages/ioc/src/container.ts +++ b/packages/ioc/src/container.ts @@ -82,14 +82,16 @@ export class Container { const existing = this.__singletons.get(key); if (!existing) { - // @jacoobes should we return false if no existing key? - throw Error("No existing key to swap for " + key); + return false; } // check if there's dispose hook, and call it if (hasCallableMethod(existing, 'dispose')) { - this.disposeAll().then(() => {; - this.registerHooks('dispose', swp); - }); + existing.dispose(); + // get the index of the existing singleton, now delete the dispose hook at that index + const hookIndex = this.hooks.get('dispose')!.indexOf(existing.dispose); + if (hookIndex > -1) { + this.hooks.get('dispose')!.splice(hookIndex, 1); + } } this.__singletons.set(key, swp); diff --git a/packages/ioc/test/index.test.ts b/packages/ioc/test/index.test.ts index 0a60e16..6ab8a99 100644 --- a/packages/ioc/test/index.test.ts +++ b/packages/ioc/test/index.test.ts @@ -125,8 +125,9 @@ describe('CoreContainer Tests', () => { expect(singletonWInit.init).toHaveBeenCalledOnce(); }); - it('should throw because not swapping anything', () => { - expect(() => coreContainer.swap('singletonKeyWithInit', singletonWInit)).toThrow() + it('should be false because not swapping anything', () => { + const swap = coreContainer.swap('singletonKeyWithInit', singletonWInit); + expect(swap).toBe(false); }) it('should swap object with another', () => { @@ -146,11 +147,18 @@ describe('CoreContainer Tests', () => { dispose: vi.fn() }; + const singletonWithDispose3 = { + value: 'singletonValueWithDispose3', + dispose: vi.fn() + }; + + coreContainer.addSingleton('singletonWithDispose3', singletonWithDispose3); const swapped = coreContainer.swap('singleton', singletonWithDispose2); expect(singletonWDispose.dispose).toHaveBeenCalledOnce(); expect(coreContainer.get>('singleton')).toBe(singletonWithDispose2); expect(singletonWithDispose2.dispose).not.toHaveBeenCalledOnce(); + expect(singletonWithDispose3.dispose).not.toHaveBeenCalledOnce(); expect(swapped).toBe(true); }) }) diff --git a/yarn.lock b/yarn.lock index 7d2288b..cd6a09a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2278,7 +2278,7 @@ __metadata: "typescript@patch:typescript@^5.0.0#~builtin": version: 5.4.5 - resolution: "typescript@patch:typescript@npm%3A5.4.5#~builtin::version=5.4.5&hash=14eedb" + resolution: "typescript@patch:typescript@npm%3A5.4.5#~builtin::version=5.4.5&hash=f3b441" bin: tsc: bin/tsc tsserver: bin/tsserver