From 5bb378040e26fd5b5c43fd66821b703aef006fc5 Mon Sep 17 00:00:00 2001 From: krutoo Date: Thu, 16 Mar 2023 16:20:27 +0500 Subject: [PATCH] #38 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - дописаны тесты DI --- src/di/__test__/application.test.ts | 15 +++++++++++++++ src/di/__test__/container.test.ts | 11 ++++++++++- src/di/application.ts | 6 +----- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/di/__test__/application.test.ts b/src/di/__test__/application.test.ts index 757fc06..3bb188d 100644 --- a/src/di/__test__/application.test.ts +++ b/src/di/__test__/application.test.ts @@ -240,4 +240,19 @@ describe('Application', () => { child.get(TOKEN.client); }).toThrow('Nothing bound to Token(config)'); }); + + it('should get component from cache', () => { + const app = createApplication(); + const token = createToken<{ id: number }>('foo'); + + const value = { id: 123 }; + app.bind(token).toValue(value); + + const first = app.get(token); + const second = app.get(token); + + expect(Object.is(value, first)).toBe(true); + expect(Object.is(value, second)).toBe(true); + expect(Object.is(first, second)).toBe(true); + }); }); diff --git a/src/di/__test__/container.test.ts b/src/di/__test__/container.test.ts index 628c853..06c8bbe 100644 --- a/src/di/__test__/container.test.ts +++ b/src/di/__test__/container.test.ts @@ -1,5 +1,5 @@ import { createContainer } from '../container'; -import { AlreadyBoundError, CircularDependencyError } from '../errors'; +import { AlreadyBoundError, CircularDependencyError, NothingBoundError } from '../errors'; import { createToken } from '../token'; describe('Container', () => { @@ -91,4 +91,13 @@ describe('Container', () => { container.get(TOKEN.bar); }).toThrow(new CircularDependencyError([TOKEN.bar, TOKEN.foo, TOKEN.baz, TOKEN.bar])); }); + + it('should throw error when nothing boud to token', () => { + const container = createContainer(); + const token = createToken('test'); + + expect(() => { + container.get(token); + }).toThrow(new NothingBoundError(token)); + }); }); diff --git a/src/di/application.ts b/src/di/application.ts index 89d882b..385bb25 100644 --- a/src/di/application.ts +++ b/src/di/application.ts @@ -79,11 +79,7 @@ class ApplicationImplementation implements Application { } if (this.providers.has(token._key)) { - const provider = this.providers.get(token._key); - - if (typeof provider !== 'function') { - throw new Error('Provider is not a function'); - } + const provider = this.providers.get(token._key) as Provider; const component = provider(otherToken => this.resolve(otherToken, nextChain()));