TSyringe
TSyringe๋
Syringe(์ฃผ์ฌ๊ธฐ) ์ฆ, ์ฃผ์ฌ๊ธฐ๋ก ์ฃผ์ ํ๋ ์ญํ ์ ํ๋ค.. ๋ฌด์์? ์์กด์ฑ์ MS์์ ๋ง๋ TypeScript์ฉ DI ๋๊ตฌ(IoC Container)
TSyringe๋ ES6์ Reflect.metadata
API์ TypeScript์ ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ํ์ฉํ์ฌ ์์กด์ฑ ์ฃผ์
์ ๊ตฌํ
External Store๋ฅผ ๊ด๋ฆฌํ๋๋ฐ ํ์ฉํ ์ ์๋ค.
์์กด์ฑ ์ค์น
npm i tsyringe reflect-metadata
์ฝ๋ ์ง์
์ ์ด ๋๋ ํ์ผ src/main.tsx
์ src/setupTexts.ts(ํ
์คํธ)
์์ reflect-metadata ์ํฌํธ
import 'reflect-metadata';
Signleton ์์
์ฑ๊ธํค์ผ๋ก ๊ด๋ฆฌํ CounterStore ํด๋์ค ์ค๋น
import { singleton } from 'tsyringe';
@singleton()
class CounterStore {
//...
}
์ฑ๊ธํค CounterStore ๊ฐ์ฒด๋ฅผ ์ฌ์ฉ
import { container } from 'tsyringe';
const counterStore = container.resolve(CounterStore);
Test Code
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { container } from 'tsyringe';
import App from './App';
const context = describe;
describe('App', () => {
function renderApp() {
return render(<App />);
}
beforeEach(() => {
container.clearInstances();
});
it('render correctly', () => {
renderApp();
expect(screen.getByText('Getting Started'));
});
context('when increase button is clicked', () => {
it('count is incremented by 1', async () => {
renderApp();
const increaseBtn = screen.getByRole('button', { name: 'Increase' });
await userEvent.click(increaseBtn);
await userEvent.click(increaseBtn);
expect(screen.getAllByText(/counter: 2/).length).toBe(2);
});
});
context('when decrease button is clicked', () => {
it('count is decrease by 1', async () => {
renderApp();
const decreaseBtn = screen.getByRole('button', { name: 'Decrease' });
await userEvent.click(decreaseBtn);
await userEvent.click(decreaseBtn);
expect(screen.getAllByText(/counter: -2/).length).toBe(2);
});
});
});
singleton (์ฑ๊ธํค)
๊ฐ์ฒด์งํฅ ๋์์ธ ํจํด ์ค ํ๋๋ก, ํน์ ํด๋์ค์ ์ธ์คํด์ค๊ฐ ์ค์ง ํ๋๋ง ์์ฑ๋๋๋ก ๋ณด์ฅํ๋ ํจํด
์ฌ๋ฌ ๊ณณ์์ ๋์ผํ ์ธ์คํด์ค๋ฅผ ๊ณต์ ํ์ฌ ์ฌ์ฉํ๊ณ ์ ํ ๋ ์ ์ฉ
์ธ๋ถ์์ ์ธ์คํด์ค๋ฅผ ์ง์ ์์ฑํ์ง ๋ชปํ๊ฒ ํด๋์ค์ ์์ฑ์๋ฅผ ๋ง์๋๋ค.
ํด๋์ค ๋ด๋ถ์์ ์ ์ผํ ์ธ์คํด์ค๋ฅผ ์์ฑํ๊ณ , ์ด๋ฅผ ๋ฐํํ๋ ์ ์ ๋ฉ์๋๋ฅผ ๊ตฌํํ์ฌ ์ ๊ณต
class SingletonClass {
private static instance: SingletonClass | null = null;
static getInstance() {
if (!this.instance) {
SingletonClass.instance = new SingletonClass();
}
return SingletonClass.instance;
}
}
Last updated