Ver3.0 ๐ฏ ํ์ ์คํฌ๋ฆฝํธ ํ ์คํ ๊ณผ Jest๋ฅผ ํ์ฉํ ํ์ ์์ ํ ๋จ์ ํ ์คํธ

๐ฏ ํ์ ์คํฌ๋ฆฝํธ ํ ์คํ ๊ณผ Jest๋ฅผ ํ์ฉํ ํ์ ์์ ํ ๋จ์ ํ ์คํธ
์น๊ตฌ์ผ, ์ด์ ์ฐ๋ฆฌ ์ฝ๋์ ์์ ๋ฒจํธ๋ฅผ ๋งค์! ๐
๐ ์ ์ฐ๋ฆฌ๋ ํ ์คํธ๋ฅผ ์์ฑํด์ผ ํ ๊น?
์ผ, ์์งํ ๋งํด์ ํ ์คํธ ์ฝ๋ ์์ฑํ๋ ๊ฑฐ ๊ท์ฐฎ์ง ์์? ๐ ๋๋ ์ฒ์์ ๊ทธ๋ฌ์ด. "์ด ์๊ฐ์ ๊ธฐ๋ฅ ํ๋ ๋ ๋ง๋๋ ๊ฒ ๋ซ์ง ์๋?" ์ถ์๊ฑฐ๋ . ๊ทผ๋ฐ ๋ง์ด์ผ, ํ๋ก์ ํธ๊ฐ ์ปค์ง๊ณ ํ์์ด ๋์ด๋๋ฉด์ ๊นจ๋ฌ์์ด. ํ ์คํธ ์ฝ๋๋ ๋ฏธ๋์ ๋๋ฅผ ์ํ ์ต๊ณ ์ ์ ๋ฌผ์ด๋ผ๋ ๊ฑธ!
ํนํ ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ฐ๋ฉด์ Jest๋ก ํ ์คํธ๋ฅผ ์์ฑํ๋ฉด, ์ ๋ง ๊ฐ๋ ฅํ ์กฐํฉ์ด ๋๊ฑฐ๋ . ํ์ ์์คํ ์ด ์ปดํ์ผ ํ์์ ์ก์์ฃผ๋ ์๋ฌ๋ค์ด ์๊ณ , ํ ์คํธ๊ฐ ๋ฐํ์์ ์ก์์ฃผ๋ ์๋ฌ๋ค์ด ์์์? ์ด ๋์ ํฉ์น๋ฉด ๊ฑฐ์ ๋ฌด์ ๋ชจ๋์ผ! ๐ก๏ธ
๐ฏ Jest๊ฐ ๋ญ๊ธธ๋?
Jest๋ ํ์ด์ค๋ถ(์ง๊ธ์ Meta)์์ ๋ง๋ ์๋ฐ์คํฌ๋ฆฝํธ ํ ์คํ ํ๋ ์์ํฌ์ผ. ๊ทผ๋ฐ ์ด๊ฒ ์ง์ง ๊ฐ๋ฐ์ ์นํ์ ์ผ๋ก ์ ๋ง๋ค์ด์ก์ด. Zero Config๋ฅผ ์งํฅํ๊ฑฐ๋ . ์ค์ ํ์ผ ๋ช ์ค๋ง ์ถ๊ฐํ๋ฉด ๋ฐ๋ก ํ ์คํธ ์์ฑ ์์ํ ์ ์์ด! ๐
1. ์ค๋
์ท ํ
์คํ
๐ธ
์ปดํฌ๋ํธ๋ ๊ฐ์ฒด์ ์ถ๋ ฅ์ ์ค๋
์ท์ผ๋ก ์ ์ฅํด๋๊ณ , ๋ค์ ํ
์คํธ์์ ๋น๊ตํ ์ ์์ด. UI ํ
์คํธํ ๋ ์ง์ง ์ ์ฉํด!
2. ๋ชจํน(Mocking) ๊ธฐ๋ฅ ๐ญ
์ธ๋ถ API ํธ์ถ์ด๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฐ๊ฒฐ ๊ฐ์ ๊ฑธ ๊ฐ์ง๋ก ๋ง๋ค์ด์ ํ
์คํธํ ์ ์์ด. ์ค์ ์๋น์ค์ ์ํฅ ์ ์ฃผ๊ณ ํ
์คํธ ๊ฐ๋ฅ!
3. ์ฝ๋ ์ปค๋ฒ๋ฆฌ์ง ๐
๋ด ์ฝ๋ ์ค์ ์ผ๋ง๋ ํ
์คํธ๋๊ณ ์๋์ง ํ๋์ ๋ณผ ์ ์์ด. ๋ชฉํ๋ 100%์ง๋ง, ํ์ค์ ์ผ๋ก 80% ์ด์์ด๋ฉด ๊ด์ฐฎ์.
4. ๋ณ๋ ฌ ์คํ โก
ํ
์คํธ๋ค์ ๋์์ ์คํํด์ ์๋๊ฐ ์์ฒญ ๋นจ๋ผ. ํฐ ํ๋ก์ ํธ์์ ์ง์ง ์ฒด๊ฐ๋ผ!
๐ง ํ์ ์คํฌ๋ฆฝํธ + Jest ํ๊ฒฝ ์ค์ ํ๊ธฐ
์, ์ด์ ๋ณธ๊ฒฉ์ ์ผ๋ก ์์ํด๋ณผ๊น? ๋จผ์ ํ๋ก์ ํธ์ ํ์ํ ํจํค์ง๋ค์ ์ค์นํด์ผ ํด. ๊ฑฑ์ ๋ง, ์๊ฐ๋ณด๋ค ๊ฐ๋จํด! ๐
npm install --save-dev jest @types/jest ts-jest typescript
npm install --save-dev @jest/globals
์ฌ๊ธฐ์ ๊ฐ ํจํค์ง๊ฐ ํ๋ ์ผ์ ๊ฐ๋จํ ์ค๋ช ํด์ค๊ฒ:
โข jest: ํ
์คํ
ํ๋ ์์ํฌ ๋ณธ์ฒด
โข @types/jest: Jest์ ํ์
์ ์ ํ์ผ (ํ์
์คํฌ๋ฆฝํธ ์ง์์ฉ)
โข ts-jest: ํ์
์คํฌ๋ฆฝํธ ํ์ผ์ Jest์์ ์คํํ ์ ์๊ฒ ํด์ฃผ๋ ๋ณํ๊ธฐ
โข typescript: ํ์
์คํฌ๋ฆฝํธ ์ปดํ์ผ๋ฌ
โข @jest/globals: Jest ์ ์ญ ํจ์๋ค์ ํ์
์ง์
ํ๋ก์ ํธ ๋ฃจํธ์ jest.config.js ํ์ผ์ ๋ง๋ค์ด์ค. ์ด๊ฒ Jest์ ๋๋ ์ญํ ์ ํด:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
'!src/**/*.test.ts'
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
};
์ด ์ค์ ์ด ๋ญ ํ๋์ง ํ๋์ฉ ๋ฏ์ด๋ณผ๊น? ๐
preset: 'ts-jest' - ํ์
์คํฌ๋ฆฝํธ ํ์ผ์ ์๋์ผ๋ก ๋ณํํด์ค
testEnvironment: 'node' - Node.js ํ๊ฒฝ์์ ํ
์คํธ ์คํ (๋ธ๋ผ์ฐ์ ํ๊ฒฝ์ด ํ์ํ๋ฉด 'jsdom' ์ฌ์ฉ)
roots - ํ
์คํธ ํ์ผ์ ์ฐพ์ ๋๋ ํ ๋ฆฌ
testMatch - ์ด๋ค ํ์ผ์ ํ
์คํธ๋ก ์ธ์ํ ์ง ํจํด ์ง์
collectCoverageFrom - ์ปค๋ฒ๋ฆฌ์ง ์ธก์ ๋์ ํ์ผ๋ค
coverageThreshold - ์ต์ ์ปค๋ฒ๋ฆฌ์ง ๊ธฐ์ค (์ด๊ฑฐ ์ ๋ง์ผ๋ฉด ๋น๋ ์คํจ!)
tsconfig.json์๋ ํ
์คํธ ๊ด๋ จ ์ค์ ์ ์ถ๊ฐํด์ค์ผ ํด:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"types": ["jest", "@types/jest", "node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.test.ts", "**/*.spec.ts"]
}
์ฌ๊ธฐ์ ์ค์ํ ๊ฑด types ๋ฐฐ์ด์ jest ๊ด๋ จ ํ์
๋ค์ ์ถ๊ฐํ๋ ๊ฑฐ์ผ. ์ด๋ ๊ฒ ํ๋ฉด ํ
์คํธ ์ฝ๋์์ describe, it, expect ๊ฐ์ ํจ์๋ค์ ํ์
์ ์๋์ผ๋ก ์ธ์ํด! ๐
๋ง์ง๋ง์ผ๋ก package.json์ ํ
์คํธ ์คํ ๋ช
๋ น์ด๋ฅผ ์ถ๊ฐํด์ค:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test:verbose": "jest --verbose"
}
}
์ด์ npm test ๋ช
๋ น์ด๋ก ํ
์คํธ๋ฅผ ์คํํ ์ ์์ด! ๊ฐ ์คํฌ๋ฆฝํธ๊ฐ ํ๋ ์ผ:
test - ๋ชจ๋ ํ
์คํธ ํ ๋ฒ ์คํ
test:watch - ํ์ผ ๋ณ๊ฒฝ ๊ฐ์งํ๋ฉด ์๋์ผ๋ก ํ
์คํธ ์ฌ์คํ (๊ฐ๋ฐํ ๋ ์ ์ฉ!)
test:coverage - ์ปค๋ฒ๋ฆฌ์ง ๋ฆฌํฌํธ ์์ฑ
test:verbose - ์์ธํ ํ
์คํธ ๊ฒฐ๊ณผ ์ถ๋ ฅ
โ๏ธ ์ฒซ ๋ฒ์งธ ํ ์คํธ ์์ฑํ๊ธฐ
์, ์ด์ ์ง์ง ํ ์คํธ๋ฅผ ์์ฑํด๋ณด์! ๊ฐ๋จํ ๊ณ์ฐ๊ธฐ ํจ์๋ถํฐ ์์ํ ๊ฒ. ๐งฎ
๋จผ์ src/calculator.ts ํ์ผ์ ๋ง๋ค์ด:
export class Calculator {
add(a: number, b: number): number {
return a + b;
}
subtract(a: number, b: number): number {
return a - b;
}
multiply(a: number, b: number): number {
return a * b;
}
divide(a: number, b: number): number {
if (b === 0) {
throw new Error('0์ผ๋ก ๋๋ ์ ์์ต๋๋ค!');
}
return a / b;
}
percentage(value: number, percent: number): number {
return (value * percent) / 100;
}
}
๋ณด๋ค์ํผ ํ์ ์คํฌ๋ฆฝํธ๋ก ์์ฑํ์ด. ๋งค๊ฐ๋ณ์์ ๋ฐํ๊ฐ์ ํ์ ์ด ๋ช ํํ์ง? ์ด๊ฒ ๋ฐ๋ก ํ์ ์์ ์ฑ์ ์์์ด์ผ! ๐ช
์ด์ src/calculator.test.ts ํ์ผ์ ๋ง๋ค์ด์ ํ
์คํธ๋ฅผ ์์ฑํด๋ณด์:
import { Calculator } from './calculator';
describe('Calculator', () => {
let calculator: Calculator;
beforeEach(() => {
calculator = new Calculator();
});
describe('add', () => {
it('๋ ์์๋ฅผ ๋ํ๋ฉด ์ฌ๋ฐ๋ฅธ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค', () => {
const result = calculator.add(2, 3);
expect(result).toBe(5);
});
it('์์์ ์์๋ฅผ ๋ํ ์ ์๋ค', () => {
const result = calculator.add(-5, 3);
expect(result).toBe(-2);
});
it('์์์ ๊ณ์ฐ์ด ์ ํํ๋ค', () => {
const result = calculator.add(0.1, 0.2);
expect(result).toBeCloseTo(0.3);
});
});
describe('divide', () => {
it('์ ์์ ์ธ ๋๋์
์ ์ํํ๋ค', () => {
const result = calculator.divide(10, 2);
expect(result).toBe(5);
});
it('0์ผ๋ก ๋๋๋ฉด ์๋ฌ๋ฅผ ๋์ง๋ค', () => {
expect(() => calculator.divide(10, 0)).toThrow('0์ผ๋ก ๋๋ ์ ์์ต๋๋ค!');
});
});
describe('percentage', () => {
it('ํผ์ผํธ ๊ณ์ฐ์ด ์ ํํ๋ค', () => {
const result = calculator.percentage(200, 15);
expect(result).toBe(30);
});
});
});
์, ์ฝ๋๊ฐ ์ข ๊ธธ์ง? ํ๋์ฉ ๋ฏ์ด๋ณด์! ๐ฌ
it (๋๋ test): ์ค์ ํ ์คํธ ์ผ์ด์ค. ํ๋์ ๋์์ ๊ฒ์ฆํด.
beforeEach: ๊ฐ ํ ์คํธ ์ ์ ์คํ๋ผ. ์ฌ๊ธฐ์ ์ด๊ธฐํ ์์ ์ ํด.
expect: ์ค์ ๊ฒ์ฆ ๋ถ๋ถ. ์์๊ฐ๊ณผ ์ค์ ๊ฐ์ ๋น๊ตํด.
ํ ์คํธ ์ด๋ฆ์ ๋ช ํํ๊ณ ๊ตฌ์ฒด์ ์ผ๋ก ์์ฑํ๋ ๊ฒ ์ค์ํด. "add ํจ์ ํ ์คํธ" ์ด๋ฐ ์์ผ๋ก ์ฐ๋ฉด ๋์ค์ ๋ญ ํ ์คํธํ๋์ง ๋ชจ๋ฅด๊ฑฐ๋ . "๋ ์์๋ฅผ ๋ํ๋ฉด ์ฌ๋ฐ๋ฅธ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค" ์ด๋ ๊ฒ ์ฐ๋ฉด ํ๋์ ์ ์ ์์ง! ๐
Jest๋ ๋ค์ํ matcher ํจ์๋ฅผ ์ ๊ณตํด. ์ํฉ์ ๋ง๊ฒ ๊ณจ๋ผ ์ฐ๋ฉด ๋ผ:
toBe(value) - ์ ํํ ๊ฐ์์ง ๋น๊ต (===)
toEqual(value) - ๊ฐ์ฒด๋ ๋ฐฐ์ด์ ๋ด์ฉ์ด ๊ฐ์์ง ๋น๊ต
toBeCloseTo(value) - ์์์ ๊ณ์ฐ์์ ๊ทผ์ฌ๊ฐ ๋น๊ต
toThrow(error) - ์๋ฌ๊ฐ ๋ฐ์ํ๋์ง ํ์ธ
toBeTruthy() / toBeFalsy() - ์ฐธ/๊ฑฐ์ง ์ฌ๋ถ ํ์ธ
toContain(item) - ๋ฐฐ์ด์ด๋ ๋ฌธ์์ด์ ํน์ ๊ฐ์ด ํฌํจ๋๋์ง
toHaveLength(number) - ๋ฐฐ์ด์ด๋ ๋ฌธ์์ด์ ๊ธธ์ด ํ์ธ
toBeGreaterThan(number) - ์ซ์ ํฌ๊ธฐ ๋น๊ต
์ด ์ธ์๋ ์์ฒญ ๋ง์! ๊ณต์ ๋ฌธ์ ๋ณด๋ฉด 30๊ฐ๊ฐ ๋๋ matcher๊ฐ ์์ด. ๐ฒ
๐ญ ๋ชจํน(Mocking)์ ์ธ๊ณ
์ค์ ํ๋ก์ ํธ์์๋ ์ธ๋ถ API๋ฅผ ํธ์ถํ๊ฑฐ๋, ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ๊ทผํ๊ฑฐ๋, ํ์ผ์ ์ฝ๊ณ ์ฐ๋ ์์ ์ด ๋ง์์? ๊ทผ๋ฐ ํ ์คํธํ ๋๋ง๋ค ์ค์ ๋ก ์ด๋ฐ ์์ ์ ํ๋ฉด ๋ฌธ์ ๊ฐ ์๊ฒจ:
โข ํ
์คํธ๊ฐ ์์ฒญ ๋๋ ค์ ธ ๐
โข ์ธ๋ถ ์๋น์ค์ ์์กดํ๊ฒ ๋ผ
โข ์ค์ ๋ฐ์ดํฐ๊ฐ ๋ณ๊ฒฝ๋ ์ ์์ด
โข ๋น์ฉ์ด ๋ฐ์ํ ์๋ ์์ด (API ํธ์ถ ์๊ธ ๋ฑ)
๊ทธ๋์ ์ฐ๋ฆฌ๋ ๋ชจํน(Mocking)์ ์ฌ์ฉํด! ๊ฐ์ง ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ ์ค์ ๋์์ ํ๋ด ๋ด๋ ๊ฑฐ์ผ. ๐ช
๊ฐ๋จํ ์์ ๋ถํฐ ๋ณผ๊น? ์ฌ์ฉ์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๋ API๊ฐ ์๋ค๊ณ ๊ฐ์ ํด๋ณด์:
// src/userService.ts
export interface User {
id: number;
name: string;
email: string;
}
export class UserService {
async fetchUser(userId: number): Promise<User> {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error('์ฌ์ฉ์๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค');
}
return response.json();
}
async getUserName(userId: number): Promise<string> {
const user = await this.fetchUser(userId);
return user.name;
}
}
์ด์ ์ด๊ฑธ ํ ์คํธํด๋ณด์. ์ค์ API๋ฅผ ํธ์ถํ์ง ์๊ณ !
// src/userService.test.ts
import { UserService, User } from './userService';
// fetch๋ฅผ ๋ชจํน
global.fetch = jest.fn();
describe('UserService', () => {
let userService: UserService;
const mockUser: User = {
id: 1,
name: '๊น์ฝ๋ฉ',
email: 'coding@example.com'
};
beforeEach(() => {
userService = new UserService();
// ๊ฐ ํ
์คํธ ์ ์ mock ์ด๊ธฐํ
jest.clearAllMocks();
});
describe('fetchUser', () => {
it('์ฌ์ฉ์ ์ ๋ณด๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ๊ฐ์ ธ์จ๋ค', async () => {
// fetch๊ฐ ์ฑ๊ณต์ ์ธ ์๋ต์ ๋ฐํํ๋๋ก ์ค์
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockUser
});
const user = await userService.fetchUser(1);
expect(user).toEqual(mockUser);
expect(global.fetch).toHaveBeenCalledWith('https://api.example.com/users/1');
expect(global.fetch).toHaveBeenCalledTimes(1);
});
it('์ฌ์ฉ์๋ฅผ ์ฐพ์ ์ ์์ผ๋ฉด ์๋ฌ๋ฅผ ๋์ง๋ค', async () => {
// fetch๊ฐ ์คํจ ์๋ต์ ๋ฐํํ๋๋ก ์ค์
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false
});
await expect(userService.fetchUser(999)).rejects.toThrow('์ฌ์ฉ์๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค');
});
});
describe('getUserName', () => {
it('์ฌ์ฉ์ ์ด๋ฆ๋ง ๋ฐํํ๋ค', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockUser
});
const name = await userService.getUserName(1);
expect(name).toBe('๊น์ฝ๋ฉ');
});
});
});
์ฌ๊ธฐ์ ํต์ฌ์ jest.fn()์ด์ผ. ์ด๊ฒ ๋ชจํน ํจ์๋ฅผ ๋ง๋ค์ด์ฃผ๊ฑฐ๋ . ๊ทธ๋ฆฌ๊ณ mockResolvedValueOnce๋ก Promise๊ฐ ๋ฐํํ ๊ฐ์ ์ง์ ํ ์ ์์ด! ๐ฏ
๋๋ก๋ ๋ชจ๋ ์ ์ฒด๋ฅผ ๋ชจํนํด์ผ ํ ๋๊ฐ ์์ด. ์๋ฅผ ๋ค์ด axios ๊ฐ์ HTTP ํด๋ผ์ด์ธํธ๋ฅผ ์ด๋ค๋ฉด:
// src/apiClient.ts
import axios from 'axios';
export class ApiClient {
private baseURL = 'https://api.example.com';
async get<T>(endpoint: string): Promise<T> {
const response = await axios.get(`${this.baseURL}${endpoint}`);
return response.data;
}
async post<T>(endpoint: string, data: any): Promise<T> {
const response = await axios.post(`${this.baseURL}${endpoint}`, data);
return response.data;
}
}
// src/apiClient.test.ts
import axios from 'axios';
import { ApiClient } from './apiClient';
// axios ๋ชจ๋ ์ ์ฒด๋ฅผ ๋ชจํน
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe('ApiClient', () => {
let apiClient: ApiClient;
beforeEach(() => {
apiClient = new ApiClient();
jest.clearAllMocks();
});
describe('get', () => {
it('GET ์์ฒญ์ ์ฑ๊ณต์ ์ผ๋ก ์ํํ๋ค', async () => {
const mockData = { id: 1, name: 'ํ
์คํธ' };
mockedAxios.get.mockResolvedValueOnce({ data: mockData });
const result = await apiClient.get('/test');
expect(result).toEqual(mockData);
expect(mockedAxios.get).toHaveBeenCalledWith('https://api.example.com/test');
});
});
describe('post', () => {
it('POST ์์ฒญ์ ์ฑ๊ณต์ ์ผ๋ก ์ํํ๋ค', async () => {
const postData = { name: '์ ํญ๋ชฉ' };
const mockResponse = { id: 2, ...postData };
mockedAxios.post.mockResolvedValueOnce({ data: mockResponse });
const result = await apiClient.post('/items', postData);
expect(result).toEqual(mockResponse);
expect(mockedAxios.post).toHaveBeenCalledWith(
'https://api.example.com/items',
postData
);
});
});
});
jest.mock('axios') ํ ์ค๋ก axios ๋ชจ๋ ์ ์ฒด๋ฅผ ๋ชจํนํ ์ ์์ด! ๊ทธ๋ฆฌ๊ณ jest.Mocked ํ์
์ ์ฌ์ฉํ๋ฉด ํ์
์คํฌ๋ฆฝํธ๊ฐ ๋ชจํน๋ ํจ์๋ค์ ํ์
์ ์ ๋๋ก ์ธ์ํด. ์ด๊ฒ ๋ฐ๋ก ํ์
์์ ํ ํ
์คํ
์ด์ผ! ๐
๋๋ก๋ ์ค์ ํจ์๋ฅผ ์คํํ๋ฉด์๋ ํธ์ถ ์ฌ๋ถ๋ฅผ ์ถ์ ํ๊ณ ์ถ์ ๋๊ฐ ์์ด. ๊ทธ๋ด ๋ ์คํ์ด๋ฅผ ์จ:
// src/logger.ts
export class Logger {
log(message: string): void {
console.log(`[LOG] ${message}`);
}
error(message: string): void {
console.error(`[ERROR] ${message}`);
}
}
export class UserManager {
constructor(private logger: Logger) {}
createUser(name: string): void {
this.logger.log(`์ฌ์ฉ์ ์์ฑ ์์: ${name}`);
// ์ค์ ์ฌ์ฉ์ ์์ฑ ๋ก์ง...
this.logger.log(`์ฌ์ฉ์ ์์ฑ ์๋ฃ: ${name}`);
}
}
// src/logger.test.ts
import { Logger, UserManager } from './logger';
describe('UserManager', () => {
let logger: Logger;
let userManager: UserManager;
beforeEach(() => {
logger = new Logger();
userManager = new UserManager(logger);
});
it('์ฌ์ฉ์ ์์ฑ ์ ๋ก๊ทธ๋ฅผ ๋จ๊ธด๋ค', () => {
// logger.log ๋ฉ์๋๋ฅผ ์คํ์ด๋ก ๊ฐ์
const logSpy = jest.spyOn(logger, 'log');
userManager.createUser('ํ๊ธธ๋');
// log๊ฐ 2๋ฒ ํธ์ถ๋์๋์ง ํ์ธ
expect(logSpy).toHaveBeenCalledTimes(2);
expect(logSpy).toHaveBeenNthCalledWith(1, '์ฌ์ฉ์ ์์ฑ ์์: ํ๊ธธ๋');
expect(logSpy).toHaveBeenNthCalledWith(2, '์ฌ์ฉ์ ์์ฑ ์๋ฃ: ํ๊ธธ๋');
// ์คํ์ด ์ ๋ฆฌ
logSpy.mockRestore();
});
});
jest.spyOn()์ ์ฐ๋ฉด ์ค์ ํจ์๋ ๊ทธ๋๋ก ์คํ๋๋ฉด์๋ ํธ์ถ ์ ๋ณด๋ฅผ ์ถ์ ํ ์ ์์ด. ๋ก๊น
์ด๋ ์ด๋ฒคํธ ๋ฐ์ ๊ฐ์ ๋ถ์ ํจ๊ณผ๋ฅผ ํ
์คํธํ ๋ ์ ์ฉํด! ๐ต๏ธ
๐๏ธ ์ค์ ์์ : ํ์ ์์ ํ ํ ์คํธ ์์ฑํ๊ธฐ
์ด์ ์ข ๋ ๋ณต์กํ ์ค์ ์์ ๋ฅผ ๋ค๋ค๋ณผ๊ฒ. ์ค์ ํ๋ก์ ํธ์์ ์์ฃผ ๋ง์ฃผ์น๋ ์ํฉ๋ค์ด์ผ! ๐ผ
์์ฆ ์น ๊ฐ๋ฐ์์ ๋น๋๊ธฐ ์์ ์ ํ์์์? Promise, async/await์ ์ ๋๋ก ํ ์คํธํ๋ ๋ฐฉ๋ฒ์ ์์๋ณด์:
// src/todoService.ts
export interface Todo {
id: number;
title: string;
completed: boolean;
userId: number;
}
export class TodoService {
private apiUrl = 'https://jsonplaceholder.typicode.com/todos';
async getTodo(id: number): Promise<Todo> {
const response = await fetch(`${this.apiUrl}/${id}`);
if (!response.ok) {
throw new Error(`Todo ${id}๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค`);
}
return response.json();
}
async getTodosByUser(userId: number): Promise<Todo[]> {
const response = await fetch(`${this.apiUrl}?userId=${userId}`);
const todos: Todo[] = await response.json();
return todos.filter(todo => todo.userId === userId);
}
async getCompletedTodos(userId: number): Promise<Todo[]> {
const todos = await this.getTodosByUser(userId);
return todos.filter(todo => todo.completed);
}
async createTodo(todo: Omit<Todo, 'id'>): Promise<Todo> {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(todo)
});
return response.json();
}
}
์ฌ๊ธฐ์ ์ฃผ๋ชฉํ ์ ์ ํ์
์คํฌ๋ฆฝํธ์ ์ ํธ๋ฆฌํฐ ํ์
์ธ Omit์ ์ฌ์ฉํ๋ค๋ ๊ฑฐ์ผ. Omit<Todo, 'id'>๋ Todo ํ์
์์ id๋ฅผ ์ ์ธํ ๋๋จธ์ง ํ๋๋ง ๊ฐ์ง ํ์
์ด์ผ. ์๋ก์ด Todo๋ฅผ ๋ง๋ค ๋ id๋ ์๋ฒ์์ ์์ฑ๋๋๊น ์ด๋ ๊ฒ ์ฐ๋ ๊ฑฐ์ง! ๐ฏ
// src/todoService.test.ts
import { TodoService, Todo } from './todoService';
global.fetch = jest.fn();
describe('TodoService', () => {
let todoService: TodoService;
const mockTodo: Todo = {
id: 1,
title: 'Jest ๊ณต๋ถํ๊ธฐ',
completed: false,
userId: 1
};
beforeEach(() => {
todoService = new TodoService();
jest.clearAllMocks();
});
describe('getTodo', () => {
it('๋จ์ผ Todo๋ฅผ ๊ฐ์ ธ์จ๋ค', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockTodo
});
const result = await todoService.getTodo(1);
expect(result).toEqual(mockTodo);
expect(global.fetch).toHaveBeenCalledWith(
'https://jsonplaceholder.typicode.com/todos/1'
);
});
it('์กด์ฌํ์ง ์๋ Todo ์กฐํ ์ ์๋ฌ๋ฅผ ๋์ง๋ค', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false
});
await expect(todoService.getTodo(999))
.rejects
.toThrow('Todo 999๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค');
});
});
describe('getTodosByUser', () => {
it('ํน์ ์ฌ์ฉ์์ ๋ชจ๋ Todo๋ฅผ ๊ฐ์ ธ์จ๋ค', async () => {
const mockTodos: Todo[] = [
{ id: 1, title: 'Todo 1', completed: false, userId: 1 },
{ id: 2, title: 'Todo 2', completed: true, userId: 1 },
{ id: 3, title: 'Todo 3', completed: false, userId: 2 }
];
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockTodos
});
const result = await todoService.getTodosByUser(1);
expect(result).toHaveLength(2);
expect(result.every(todo => todo.userId === 1)).toBe(true);
});
});
describe('getCompletedTodos', () => {
it('์๋ฃ๋ Todo๋ง ํํฐ๋งํ๋ค', async () => {
const mockTodos: Todo[] = [
{ id: 1, title: 'Todo 1', completed: false, userId: 1 },
{ id: 2, title: 'Todo 2', completed: true, userId: 1 },
{ id: 3, title: 'Todo 3', completed: true, userId: 1 }
];
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockTodos
});
const result = await todoService.getCompletedTodos(1);
expect(result).toHaveLength(2);
expect(result.every(todo => todo.completed)).toBe(true);
});
});
describe('createTodo', () => {
it('์๋ก์ด Todo๋ฅผ ์์ฑํ๋ค', async () => {
const newTodo: Omit<Todo, 'id'> = {
title: '์๋ก์ด ํ ์ผ',
completed: false,
userId: 1
};
const createdTodo: Todo = { id: 201, ...newTodo };
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => createdTodo
});
const result = await todoService.createTodo(newTodo);
expect(result).toEqual(createdTodo);
expect(global.fetch).toHaveBeenCalledWith(
'https://jsonplaceholder.typicode.com/todos',
expect.objectContaining({
method: 'POST',
headers: { 'Content-Type': 'application/json' }
})
);
});
});
});
๋น๋๊ธฐ ํ
์คํธ์์ ์ค์ํ ๊ฑด async/await์ ์ ๋๋ก ์ฐ๋ ๊ฑฐ์ผ. ๊ทธ๋ฆฌ๊ณ rejects matcher๋ฅผ ์ฐ๋ฉด Promise๊ฐ reject๋๋ ๊ฑธ ํ
์คํธํ ์ ์์ด! ๐
๋น๋๊ธฐ ํ ์คํธ์์ await์ ๋นผ๋จน์ผ๋ฉด ํ ์คํธ๊ฐ ๋๋๊ธฐ ์ ์ Promise๊ฐ resolve๋์ง ์์์ ํญ์ ํต๊ณผํด๋ฒ๋ ค. ๋ฐ๋์ await์ ๋ถ์ด๊ฑฐ๋ return์ ์จ์ค์ผ ํด!
ํ์ ์คํฌ๋ฆฝํธ์ ์ ๋ค๋ฆญ์ ์ ๋ง ๊ฐ๋ ฅํ ๊ธฐ๋ฅ์ด์ผ. ํ ์คํธ์์๋ ์ ๋ค๋ฆญ์ ํ์ฉํ๋ฉด ํ์ ์์ ์ฑ์ ๋ ๋์ผ ์ ์์ด:
// src/repository.ts
export interface Entity {
id: number;
}
export class Repository<T extends Entity> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
findById(id: number): T | undefined {
return this.items.find(item => item.id === id);
}
findAll(): T[] {
return [...this.items];
}
update(id: number, updates: Partial<T>): T | undefined {
const index = this.items.findIndex(item => item.id === id);
if (index === -1) return undefined;
this.items[index] = { ...this.items[index], ...updates };
return this.items[index];
}
delete(id: number): boolean {
const index = this.items.findIndex(item => item.id === id);
if (index === -1) return false;
this.items.splice(index, 1);
return true;
}
count(): number {
return this.items.length;
}
}
// src/repository.test.ts
import { Repository, Entity } from './repository';
interface User extends Entity {
name: string;
email: string;
}
interface Product extends Entity {
name: string;
price: number;
}
describe('Repository', () => {
describe('User Repository', () => {
let userRepo: Repository<User>;
beforeEach(() => {
userRepo = new Repository<User>();
});
it('์ฌ์ฉ์๋ฅผ ์ถ๊ฐํ ์ ์๋ค', () => {
const user: User = { id: 1, name: '๊น์ฒ ์', email: 'kim@test.com' };
userRepo.add(user);
expect(userRepo.count()).toBe(1);
expect(userRepo.findById(1)).toEqual(user);
});
it('์ฌ์ฉ์ ์ ๋ณด๋ฅผ ์์ ํ ์ ์๋ค', () => {
const user: User = { id: 1, name: '๊น์ฒ ์', email: 'kim@test.com' };
userRepo.add(user);
const updated = userRepo.update(1, { name: '๊น์ํฌ' });
expect(updated).toBeDefined();
expect(updated?.name).toBe('๊น์ํฌ');
expect(updated?.email).toBe('kim@test.com'); // ์ด๋ฉ์ผ์ ๊ทธ๋๋ก
});
it('์กด์ฌํ์ง ์๋ ์ฌ์ฉ์ ์์ ์ undefined๋ฅผ ๋ฐํํ๋ค', () => {
const result = userRepo.update(999, { name: '์๋์ฌ๋' });
expect(result).toBeUndefined();
});
it('์ฌ์ฉ์๋ฅผ ์ญ์ ํ ์ ์๋ค', () => {
const user: User = { id: 1, name: '๊น์ฒ ์', email: 'kim@test.com' };
userRepo.add(user);
const deleted = userRepo.delete(1);
expect(deleted).toBe(true);
expect(userRepo.count()).toBe(0);
expect(userRepo.findById(1)).toBeUndefined();
});
});
describe('Product Repository', () => {
let productRepo: Repository<Product>;
beforeEach(() => {
productRepo = new Repository<Product>();
});
it('์ํ์ ์ถ๊ฐํ๊ณ ์กฐํํ ์ ์๋ค', () => {
const product: Product = { id: 1, name: '๋
ธํธ๋ถ', price: 1500000 };
productRepo.add(product);
const found = productRepo.findById(1);
expect(found).toEqual(product);
});
it('๋ชจ๋ ์ํ์ ์กฐํํ ์ ์๋ค', () => {
const products: Product[] = [
{ id: 1, name: '๋
ธํธ๋ถ', price: 1500000 },
{ id: 2, name: '๋ง์ฐ์ค', price: 30000 },
{ id: 3, name: 'ํค๋ณด๋', price: 80000 }
];
products.forEach(p => productRepo.add(p));
const all = productRepo.findAll();
expect(all).toHaveLength(3);
expect(all).toEqual(products);
});
it('์ํ ๊ฐ๊ฒฉ์ ์์ ํ ์ ์๋ค', () => {
const product: Product = { id: 1, name: '๋
ธํธ๋ถ', price: 1500000 };
productRepo.add(product);
productRepo.update(1, { price: 1200000 });
const updated = productRepo.findById(1);
expect(updated?.price).toBe(1200000);
});
});
});
์ ๋ค๋ฆญ์ ์ฐ๋ฉด ๊ฐ์ Repository ํด๋์ค๋ก User๋ ๊ด๋ฆฌํ๊ณ Product๋ ๊ด๋ฆฌํ ์ ์์ด. ๊ทธ๋ฆฌ๊ณ ํ์ ์คํฌ๋ฆฝํธ๊ฐ ๊ฐ๊ฐ์ ํ์ ์ ์ ํํ ์ถ๋ก ํด์ฃผ๋๊น ํ ์คํธ ์์ฑํ ๋๋ ์๋์์ฑ์ด ์๋ฒฝํ๊ฒ ๋์ํด! ์ด๊ฒ ๋ฐ๋ก ํ์ ์์ ํ ๊ฐ๋ฐ์ ๋งค๋ ฅ์ด์ผ! โจ
๐จ ํ ์คํธ ์ปค๋ฒ๋ฆฌ์ง์ ํ์ง ๊ด๋ฆฌ
ํ ์คํธ๋ฅผ ์์ฑํ๋ ๊ฒ๋ ์ค์ํ์ง๋ง, ์ผ๋ง๋ ์ ์ปค๋ฒํ๊ณ ์๋์ง ์ธก์ ํ๋ ๊ฒ๋ ์ค์ํด. ์ปค๋ฒ๋ฆฌ์ง๋ ์ฝ๋์ ์ด๋ ๋ถ๋ถ์ด ํ ์คํธ๋๊ณ ์๋์ง ๋ณด์ฌ์ฃผ๋ ์งํ์ผ! ๐
์๊น ์ค์ ํ ๋๋ก npm run test:coverage๋ฅผ ์คํํ๋ฉด ์ปค๋ฒ๋ฆฌ์ง ๋ฆฌํฌํธ๊ฐ ์์ฑ๋ผ:
npm run test:coverage
๊ทธ๋ฌ๋ฉด ํฐ๋ฏธ๋์ ์ด๋ฐ ์์ผ๋ก ๊ฒฐ๊ณผ๊ฐ ๋์:
--------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files | 92.31 | 88.89 | 100 | 91.67 |
calculator.ts | 100 | 100 | 100 | 100 |
todoService.ts | 88.89 | 83.33 | 100 | 87.50 | 15,23
repository.ts | 95.45 | 90.91 | 100 | 94.74 | 28
--------------------|---------|----------|---------|---------|-------------------
๊ฐ ํญ๋ชฉ์ด ๋ญ ์๋ฏธํ๋์ง ์์๋ณด์:
% Stmts (Statements) - ์คํ๋ ๊ตฌ๋ฌธ์ ๋น์จ
% Branch - if/else ๊ฐ์ ๋ถ๊ธฐ๋ฌธ์ ๋ชจ๋ ๊ฒฝ๋ก๊ฐ ํ
์คํธ๋ ๋น์จ
% Funcs (Functions) - ํธ์ถ๋ ํจ์์ ๋น์จ
% Lines - ์คํ๋ ์ฝ๋ ๋ผ์ธ์ ๋น์จ
Uncovered Line #s - ํ
์คํธ๋์ง ์์ ๋ผ์ธ ๋ฒํธ
๊ทธ๋ฆฌ๊ณ coverage ํด๋์ HTML ๋ฆฌํฌํธ๋ ์์ฑ๋ผ. ๋ธ๋ผ์ฐ์ ๋ก ์ด์ด๋ณด๋ฉด ์๊ฐ์ ์ผ๋ก ์ด๋ ๋ถ๋ถ์ด ์ปค๋ฒ๋์ง ์์๋์ง ํ๋์ ๋ณผ ์ ์์ด! ๐จ
โข ํต์ฌ ๋น์ฆ๋์ค ๋ก์ง: 90% ์ด์
โข ์ ํธ๋ฆฌํฐ ํจ์: 80% ์ด์
โข UI ์ปดํฌ๋ํธ: 70% ์ด์
์ด ์ ๋๋ฉด ๊ด์ฐฎ์!
์ปค๋ฒ๋ฆฌ์ง๊ฐ ๋๋ค๊ณ ํด์ ํ ์คํธ ํ์ง์ด ์ข์ ๊ฑด ์๋์ผ. ์๋ฏธ ์๋ ํ ์คํธ๋ฅผ ์์ฑํ๋ ๊ฒ ์ค์ํด! ๐ฏ
1. AAA ํจํด ๋ฐ๋ฅด๊ธฐ
Arrange(์ค๋น), Act(์คํ), Assert(๊ฒ์ฆ) ํจํด์ ๋ฐ๋ฅด๋ฉด ํ
์คํธ๊ฐ ๋ช
ํํด์ ธ:
it('์ฌ์ฉ์ ๋์ด๋ฅผ ๊ณ์ฐํ๋ค', () => {
// Arrange - ํ
์คํธ ์ค๋น
const birthYear = 1990;
const currentYear = 2024;
// Act - ์ค์ ๋์ ์คํ
const age = currentYear - birthYear;
// Assert - ๊ฒฐ๊ณผ ๊ฒ์ฆ
expect(age).toBe(34);
});
2. ํ๋์ ํ
์คํธ๋ ํ๋์ ๊ฒ๋ง ๊ฒ์ฆ
ํ
์คํธ ํ๋์ ๋๋ฌด ๋ง์ ๊ฑธ ๋ฃ์ง ๋ง. ์คํจํ์ ๋ ์์ธ ์ฐพ๊ธฐ ์ด๋ ค์์ ธ:
// โ ๋์ ์
it('์ฌ์ฉ์ ๊ด๋ จ ๋ชจ๋ ๊ธฐ๋ฅ', () => {
const user = createUser('ํ๊ธธ๋');
expect(user.name).toBe('ํ๊ธธ๋');
updateUser(user, { age: 30 });
expect(user.age).toBe(30);
deleteUser(user);
expect(findUser(user.id)).toBeUndefined();
});
// โ
์ข์ ์
describe('User ๊ด๋ฆฌ', () => {
it('์ฌ์ฉ์๋ฅผ ์์ฑํ๋ค', () => {
const user = createUser('ํ๊ธธ๋');
expect(user.name).toBe('ํ๊ธธ๋');
});
it('์ฌ์ฉ์ ์ ๋ณด๋ฅผ ์์ ํ๋ค', () => {
const user = createUser('ํ๊ธธ๋');
updateUser(user, { age: 30 });
expect(user.age).toBe(30);
});
it('์ฌ์ฉ์๋ฅผ ์ญ์ ํ๋ค', () => {
const user = createUser('ํ๊ธธ๋');
deleteUser(user);
expect(findUser(user.id)).toBeUndefined();
});
});
3. ์ฃ์ง ์ผ์ด์ค ํ
์คํธํ๊ธฐ
์ ์์ ์ธ ๊ฒฝ์ฐ๋ง ํ
์คํธํ๋ฉด ์ ๋ผ. ์์ธ ์ํฉ๋ ๊ผญ ํ
์คํธํด์ผ ํด:
describe('divide ํจ์', () => {
it('์ ์์ ์ธ ๋๋์
', () => {
expect(divide(10, 2)).toBe(5);
});
it('0์ผ๋ก ๋๋๊ธฐ', () => {
expect(() => divide(10, 0)).toThrow();
});
it('์์ ๋๋๊ธฐ', () => {
expect(divide(-10, 2)).toBe(-5);
});
it('์์์ ๋๋๊ธฐ', () => {
expect(divide(1, 3)).toBeCloseTo(0.333, 2);
});
it('๋งค์ฐ ํฐ ์ ๋๋๊ธฐ', () => {
expect(divide(Number.MAX_SAFE_INTEGER, 2)).toBeLessThan(Number.MAX_SAFE_INTEGER);
});
});
4. ํ
์คํธ ์ด๋ฆ์ ๋ช
ํํ๊ฒ
ํ
์คํธ ์ด๋ฆ๋ง ๋ด๋ ๋ฌด์์ ํ
์คํธํ๋์ง ์ ์ ์์ด์ผ ํด:
// โ ๋์ ์
it('test1', () => { ... });
it('works', () => { ... });
// โ
์ข์ ์
it('๋น ๋ฌธ์์ด์ ์
๋ ฅํ๋ฉด ์๋ฌ๋ฅผ ๋์ง๋ค', () => { ... });
it('์ ํจํ ์ด๋ฉ์ผ ํ์์ด๋ฉด true๋ฅผ ๋ฐํํ๋ค', () => { ... });
๐ฅ ๊ณ ๊ธ ํ ์คํ ๊ธฐ๋ฒ
์ด์ ์ข ๋ ๊ณ ๊ธ ๊ธฐ๋ฒ๋ค์ ์์๋ณผ๊น? ์ค๋ฌด์์ ์ ๋ง ์ ์ฉํ ํ ํฌ๋๋ค์ด์ผ! ๐
๊ฐ์ ๋ก์ง์ ์ฌ๋ฌ ์
๋ ฅ๊ฐ์ผ๋ก ํ
์คํธํ๊ณ ์ถ์ ๋๊ฐ ์์์? ๊ทธ๋ด ๋ test.each๋ฅผ ์ฐ๋ฉด ์ฝ๋ ์ค๋ณต์ ์ค์ผ ์ ์์ด:
// src/validator.ts
export class Validator {
isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
isValidPassword(password: string): boolean {
// ์ต์ 8์, ๋๋ฌธ์, ์๋ฌธ์, ์ซ์ ํฌํจ
return password.length >= 8 &&
/[A-Z]/.test(password) &&
/[a-z]/.test(password) &&
/[0-9]/.test(password);
}
isValidPhoneNumber(phone: string): boolean {
const phoneRegex = /^01[0-9]-?[0-9]{4}-?[0-9]{4}$/;
return phoneRegex.test(phone);
}
}
// src/validator.test.ts
import { Validator } from './validator';
describe('Validator', () => {
let validator: Validator;
beforeEach(() => {
validator = new Validator();
});
describe('isValidEmail', () => {
// ์ ํจํ ์ด๋ฉ์ผ ํ
์คํธ
test.each([
['test@example.com'],
['user.name@domain.co.kr'],
['admin+tag@company.com'],
['123@test.org']
])('"%s"๋ ์ ํจํ ์ด๋ฉ์ผ์ด๋ค', (email) => {
expect(validator.isValidEmail(email)).toBe(true);
});
// ์ ํจํ์ง ์์ ์ด๋ฉ์ผ ํ
์คํธ
test.each([
['invalid'],
['@example.com'],
['test@'],
['test @example.com'],
['']
])('"%s"๋ ์ ํจํ์ง ์์ ์ด๋ฉ์ผ์ด๋ค', (email) => {
expect(validator.isValidEmail(email)).toBe(false);
});
});
describe('isValidPassword', () => {
test.each([
['Password123', true],
['SecurePass1', true],
['MyP@ssw0rd', true],
['short1A', false], // ๋๋ฌด ์งง์
['nouppercase1', false], // ๋๋ฌธ์ ์์
['NOLOWERCASE1', false], // ์๋ฌธ์ ์์
['NoNumber', false], // ์ซ์ ์์
['', false] // ๋น ๋ฌธ์์ด
])('๋น๋ฐ๋ฒํธ "%s"์ ์ ํจ์ฑ์ %s์ด๋ค', (password, expected) => {
expect(validator.isValidPassword(password)).toBe(expected);
});
});
describe('isValidPhoneNumber', () => {
test.each([
['010-1234-5678', true],
['01012345678', true],
['011-123-4567', true],
['02-1234-5678', false], // ์ง์ญ๋ฒํธ
['010-123-4567', false], // ์๋ฆฟ์ ํ๋ฆผ
['abc-defg-hijk', false], // ์ซ์ ์๋
['', false]
])('์ ํ๋ฒํธ "%s"์ ์ ํจ์ฑ์ %s์ด๋ค', (phone, expected) => {
expect(validator.isValidPhoneNumber(phone)).toBe(expected);
});
});
});
test.each๋ฅผ ์ฐ๋ฉด ํ
์คํธ ์ผ์ด์ค๋ฅผ ๋ฐฐ์ด๋ก ์ ์ํ ์ ์์ด. ์๋ก์ด ์ผ์ด์ค ์ถ๊ฐํ ๋๋ ๋ฐฐ์ด์ ํ ์ค๋ง ์ถ๊ฐํ๋ฉด ๋ผ! ์์ฒญ ํธํ์ง? ๐
setTimeout์ด๋ setInterval์ ์ฌ์ฉํ๋ ์ฝ๋๋ฅผ ํ ์คํธํ ๋๋ ์ค์ ๋ก ์๊ฐ์ด ์ง๋๊ธธ ๊ธฐ๋ค๋ฆฌ๋ฉด ์ ๋ผ. Jest์ ํ์ด๋จธ ๋ชจํน ๊ธฐ๋ฅ์ ์จ์ผ ํด:
// src/scheduler.ts
export class Scheduler {
private timerId: NodeJS.Timeout | null = null;
scheduleTask(callback: () => void, delay: number): void {
this.timerId = setTimeout(callback, delay);
}
repeatTask(callback: () => void, interval: number): void {
this.timerId = setInterval(callback, interval);
}
cancel(): void {
if (this.timerId) {
clearTimeout(this.timerId);
clearInterval(this.timerId);
this.timerId = null;
}
}
}
export class RateLimiter {
private lastCallTime = 0;
private readonly minInterval: number;
constructor(minInterval: number) {
this.minInterval = minInterval;
}
canCall(): boolean {
const now = Date.now();
if (now - this.lastCallTime >= this.minInterval) {
this.lastCallTime = now;
return true;
}
return false;
}
}
// src/scheduler.test.ts
import { Scheduler, RateLimiter } from './scheduler';
describe('Scheduler', () => {
let scheduler: Scheduler;
beforeEach(() => {
scheduler = new Scheduler();
jest.useFakeTimers(); // ๊ฐ์ง ํ์ด๋จธ ์ฌ์ฉ
});
afterEach(() => {
scheduler.cancel();
jest.useRealTimers(); // ์ค์ ํ์ด๋จธ๋ก ๋ณต์
});
it('์ง์ ๋ ์๊ฐ ํ์ ์ฝ๋ฐฑ์ ์คํํ๋ค', () => {
const callback = jest.fn();
scheduler.scheduleTask(callback, 1000);
// ์์ง ์คํ ์ ๋จ
expect(callback).not.toHaveBeenCalled();
// 1์ด ์งํ
jest.advanceTimersByTime(1000);
// ์ด์ ์คํ๋จ
expect(callback).toHaveBeenCalledTimes(1);
});
it('๋ฐ๋ณต ์์
์ ์คํํ๋ค', () => {
const callback = jest.fn();
scheduler.repeatTask(callback, 500);
// 0.5์ด๋ง๋ค ์คํ
jest.advanceTimersByTime(500);
expect(callback).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(500);
expect(callback).toHaveBeenCalledTimes(2);
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(4);
});
it('์์
์ ์ทจ์ํ ์ ์๋ค', () => {
const callback = jest.fn();
scheduler.scheduleTask(callback, 1000);
scheduler.cancel();
jest.advanceTimersByTime(1000);
// ์ทจ์ํ์ผ๋ฏ๋ก ์คํ ์ ๋จ
expect(callback).not.toHaveBeenCalled();
});
});
describe('RateLimiter', () => {
beforeEach(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2024-01-01T00:00:00'));
});
afterEach(() => {
jest.useRealTimers();
});
it('์ต์ ๊ฐ๊ฒฉ ๋ด์๋ ํธ์ถ์ ์ ํํ๋ค', () => {
const limiter = new RateLimiter(1000); // 1์ด ๊ฐ๊ฒฉ
expect(limiter.canCall()).toBe(true); // ์ฒซ ํธ์ถ ์ฑ๊ณต
expect(limiter.canCall()).toBe(false); // ์ฆ์ ์ฌํธ์ถ ์คํจ
jest.advanceTimersByTime(500);
expect(limiter.canCall()).toBe(false); // 0.5์ด ํ์๋ ์คํจ
jest.advanceTimersByTime(500);
expect(limiter.canCall()).toBe(true); // 1์ด ํ ์ฑ๊ณต
});
});
jest.useFakeTimers()๋ฅผ ์ฐ๋ฉด ์๊ฐ์ ๋ง์๋๋ก ์กฐ์ํ ์ ์์ด! jest.advanceTimersByTime()์ผ๋ก ์๊ฐ์ ๋นจ๋ฆฌ ๊ฐ๊ธฐํ ์ ์๊ณ , jest.setSystemTime()์ผ๋ก ํน์ ์์ ์ผ๋ก ์ค์ ํ ์๋ ์์ด. ์๊ฐ ๊ด๋ จ ํ
์คํธ๊ฐ ๋ช ์ด ๋ง์ ๋๋! โฐ
์์ฆ ์คํธ๋ฆฌ๋ฐ API๋ ๋์ฉ๋ ๋ฐ์ดํฐ ์ฒ๋ฆฌ์์ ๋น๋๊ธฐ ์ดํฐ๋ ์ดํฐ๋ฅผ ๋ง์ด ์ฐ์์? ์ด๊ฒ๋ ํ ์คํธํ ์ ์์ด:
// src/dataStream.ts
export class DataStream<T> {
constructor(private data: T[], private chunkSize: number = 1) {}
async *[Symbol.asyncIterator](): AsyncIterator<T[]> {
for (let i = 0; i < this.data.length; i += this.chunkSize) {
// ๋น๋๊ธฐ ์์
์๋ฎฌ๋ ์ด์
await new Promise(resolve => setTimeout(resolve, 10));
yield this.data.slice(i, i + this.chunkSize);
}
}
async toArray(): Promise<T[]> {
const result: T[] = [];
for await (const chunk of this) {
result.push(...chunk);
}
return result;
}
async filter(predicate: (item: T) => boolean): Promise<T[]> {
const result: T[] = [];
for await (const chunk of this) {
result.push(...chunk.filter(predicate));
}
return result;
}
}
// src/dataStream.test.ts
import { DataStream } from './dataStream';
describe('DataStream', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('๋ฐ์ดํฐ๋ฅผ ์ฒญํฌ ๋จ์๋ก ์คํธ๋ฆฌ๋ฐํ๋ค', async () => {
const data = [1, 2, 3, 4, 5];
const stream = new DataStream(data, 2);
const chunks: number[][] = [];
const iteratorPromise = (async () => {
for await (const chunk of stream) {
chunks.push(chunk);
}
})();
// ํ์ด๋จธ๋ฅผ ์งํ์์ผ ๋น๋๊ธฐ ์์
์๋ฃ
await jest.runAllTimersAsync();
await iteratorPromise;
expect(chunks).toEqual([[1, 2], [3, 4], [5]]);
});
it('์ ์ฒด ๋ฐ์ดํฐ๋ฅผ ๋ฐฐ์ด๋ก ๋ณํํ๋ค', async () => {
const data = [1, 2, 3, 4, 5];
const stream = new DataStream(data, 2);
const resultPromise = stream.toArray();
await jest.runAllTimersAsync();
const result = await resultPromise;
expect(result).toEqual(data);
});
it('์กฐ๊ฑด์ ๋ง๋ ๋ฐ์ดํฐ๋ง ํํฐ๋งํ๋ค', async () => {
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stream = new DataStream(data, 3);
const resultPromise = stream.filter(n => n % 2 === 0);
await jest.runAllTimersAsync();
const result = await resultPromise;
expect(result).toEqual([2, 4, 6, 8, 10]);
});
});
๋น๋๊ธฐ ์ดํฐ๋ ์ดํฐ๋ for await...of ๊ตฌ๋ฌธ์ผ๋ก ํ
์คํธํ ์ ์์ด. ๊ทธ๋ฆฌ๊ณ jest.runAllTimersAsync()๋ฅผ ์ฐ๋ฉด ๋ชจ๋ ๋น๋๊ธฐ ํ์ด๋จธ๋ฅผ ํ ๋ฒ์ ์ฒ๋ฆฌํ ์ ์์ด! ๐
๐ ๏ธ ์ค๋ฌด ํ๊ณผ ๋ฒ ์คํธ ํ๋ํฐ์ค
์ด์ ์ค๋ฌด์์ ์ ๋ง ์ ์ฉํ ํ๋ค์ ๊ณต์ ํ ๊ฒ. ๋ด๊ฐ ๋ช ๋ ๊ฐ ์ฝ์งํ๋ฉด์ ๋ฐฐ์ด ๊ฒ๋ค์ด์ผ! ๐
๋ฐ๋ณต๋๋ ์ค์ ์ฝ๋๋ ํฌํผ ํจ์๋ก ๋ง๋ค์ด๋๋ฉด ํธํด:
// src/__tests__/helpers/testHelpers.ts
import { User, Product } from '../../types';
export class TestDataBuilder {
static createUser(overrides?: Partial<User>): User {
return {
id: 1,
name: 'ํ
์คํธ์ ์ ',
email: 'test@example.com',
age: 25,
createdAt: new Date('2024-01-01'),
...overrides
};
}
static createProduct(overrides?: Partial<Product>): Product {
return {
id: 1,
name: 'ํ
์คํธ์ํ',
price: 10000,
stock: 100,
category: 'electronics',
...overrides
};
}
static createUsers(count: number): User[] {
return Array.from({ length: count }, (_, i) =>
this.createUser({ id: i + 1, name: `์ ์ ${i + 1}` })
);
}
}
export class MockFactory {
static createMockFetch(data: any, ok = true) {
return jest.fn().mockResolvedValue({
ok,
json: async () => data,
text: async () => JSON.stringify(data)
});
}
static createMockLocalStorage() {
const store: Record<string, string> = {};
return {
getItem: jest.fn((key: string) => store[key] || null),
setItem: jest.fn((key: string, value: string) => {
store[key] = value;
}),
removeItem: jest.fn((key: string) => {
delete store[key];
}),
clear: jest.fn(() => {
Object.keys(store).forEach(key => delete store[key]);
})
};
}
}
export const waitFor = async (
callback: () => boolean,
timeout = 1000,
interval = 50
): Promise<void> {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
if (callback()) return;
await new Promise(resolve => setTimeout(resolve, interval));
}
throw new Error('Timeout waiting for condition');
};
์ด๋ฐ ํฌํผ๋ค์ ๋ง๋ค์ด๋๋ฉด ํ ์คํธ ์ฝ๋๊ฐ ํจ์ฌ ๊น๋ํด์ ธ:
// ํฌํผ ์ฌ์ฉ ์
it('์ฌ์ฉ์๋ฅผ ์์ฑํ๋ค', () => {
const user = {
id: 1,
name: 'ํ๊ธธ๋',
email: 'hong@test.com',
age: 30,
createdAt: new Date()
};
// ...
});
// ํฌํผ ์ฌ์ฉ ํ
it('์ฌ์ฉ์๋ฅผ ์์ฑํ๋ค', () => {
const user = TestDataBuilder.createUser({ name: 'ํ๊ธธ๋', age: 30 });
// ...
});
ํ ์คํธ ํ๊ฒฝ์์๋ ์ค์ ํ๊ฒฝ ๋ณ์๋ฅผ ์ฐ๋ฉด ์ ๋ผ. ํ ์คํธ์ฉ ์ค์ ์ ๋ฐ๋ก ๋ง๋ค์ด์ผ ํด:
// jest.setup.ts
process.env.NODE_ENV = 'test';
process.env.API_URL = 'http://localhost:3000';
process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/testdb';
// ์ ์ญ ๋ชจํน ์ค์
global.fetch = jest.fn();
// ์ฝ์ ์๋ฌ ๋ฌด์ (ํ
์คํธ ์ค ์๋์ ์ธ ์๋ฌ)
const originalError = console.error;
beforeAll(() => {
console.error = jest.fn();
});
afterAll(() => {
console.error = originalError;
});
๊ทธ๋ฆฌ๊ณ jest.config.js์ ์ค์ ํ์ผ์ ์ถ๊ฐํด:
module.exports = {
// ... ๊ธฐ์กด ์ค์
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
};
GitHub Actions๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ์ด๋ฐ ์ํฌํ๋ก์ฐ๋ฅผ ๋ง๋ค ์ ์์ด:
# .github/workflows/test.yml
name: Test
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test -- --coverage
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
flags: unittests
name: codecov-umbrella
- name: Check coverage threshold
run: |
npm run test:coverage
if [ $? -ne 0 ]; then
echo "Coverage threshold not met!"
exit 1
fi
์ด๋ ๊ฒ ํ๋ฉด PR์ ์ฌ๋ฆด ๋๋ง๋ค ์๋์ผ๋ก ํ ์คํธ๊ฐ ์คํ๋๊ณ , ์ปค๋ฒ๋ฆฌ์ง๊ฐ ๊ธฐ์ค์ ๋ชป ๋ฏธ์น๋ฉด ๋จธ์ง๋ฅผ ๋ง์ ์ ์์ด! ๐ซ
ํ ์คํธ๊ฐ ๋ง์์ง๋ฉด ์คํ ์๊ฐ์ด ๊ธธ์ด์ ธ. ๋ช ๊ฐ์ง ์ต์ ํ ๋ฐฉ๋ฒ์ด ์์ด:
1. ๋ณ๋ ฌ ์คํ ํ์ฉ
Jest๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ณ๋ ฌ ์คํ์ ํ์ง๋ง, ์์ปค ์๋ฅผ ์กฐ์ ํ ์ ์์ด:
// jest.config.js
module.exports = {
// ...
maxWorkers: '50%', // CPU ์ฝ์ด์ 50%๋ง ์ฌ์ฉ
// ๋๋
maxWorkers: 4, // 4๊ฐ์ ์์ปค ์ฌ์ฉ
};
2. ํ
์คํธ ํ์ผ ํํฐ๋ง
ํน์ ํ์ผ๋ง ํ
์คํธํ๊ณ ์ถ์ ๋:
npm test -- calculator.test.ts
npm test -- --testPathPattern=user
3. ์บ์ฑ ํ์ฉ
Jest๋ ๋ณ๊ฒฝ๋ ํ์ผ๋ง ๋ค์ ํ
์คํธํด:
npm test -- --onlyChanged
npm test -- --watch # ๋ณ๊ฒฝ ๊ฐ์ง ๋ชจ๋
4. ๋ฌด๊ฑฐ์ด ๋ชจํน ์ต์ํ
๋ชจ๋ ๊ฑธ ๋ชจํนํ๋ฉด ์คํ๋ ค ๋๋ ค์ง ์ ์์ด. ํ์ํ ๊ฒ๋ง ๋ชจํนํด!
๐ ์ค์ ํ๋ก์ ํธ ์์
๋ง์ง๋ง์ผ๋ก ์ค์ ํ๋ก์ ํธ์์ ์ฌ์ฉํ ๋งํ ์์ ํ ์์ ๋ฅผ ๋ณด์ฌ์ค๊ฒ. ๊ฐ๋จํ ์ผํ๋ชฐ ์ฅ๋ฐ๊ตฌ๋ ์์คํ ์ด์ผ! ๐
// src/cart/types.ts
export interface Product {
id: string;
name: string;
price: number;
stock: number;
}
export interface CartItem {
product: Product;
quantity: number;
}
export interface Cart {
items: CartItem[];
total: number;
}
export interface DiscountRule {
type: 'percentage' | 'fixed';
value: number;
minAmount?: number;
}
// src/cart/CartService.ts
import { Product, CartItem, Cart, DiscountRule } from './types';
export class CartService {
private items: Map<string, CartItem> = new Map();
addItem(product: Product, quantity: number = 1): void {
if (quantity <= 0) {
throw new Error('์๋์ 1 ์ด์์ด์ด์ผ ํฉ๋๋ค');
}
if (quantity > product.stock) {
throw new Error(`์ฌ๊ณ ๊ฐ ๋ถ์กฑํฉ๋๋ค. ํ์ฌ ์ฌ๊ณ : ${product.stock}`);
}
const existingItem = this.items.get(product.id);
if (existingItem) {
const newQuantity = existingItem.quantity + quantity;
if (newQuantity > product.stock) {
throw new Error('์ฌ๊ณ ๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค');
}
existingItem.quantity = newQuantity;
} else {
this.items.set(product.id, { product, quantity });
}
}
removeItem(productId: string): void {
if (!this.items.has(productId)) {
throw new Error('์ฅ๋ฐ๊ตฌ๋์ ํด๋น ์ํ์ด ์์ต๋๋ค');
}
this.items.delete(productId);
}
updateQuantity(productId: string, quantity: number): void {
const item = this.items.get(productId);
if (!item) {
throw new Error('์ฅ๋ฐ๊ตฌ๋์ ํด๋น ์ํ์ด ์์ต๋๋ค');
}
if (quantity <= 0) {
this.removeItem(productId);
return;
}
if (quantity > item.product.stock) {
throw new Error('์ฌ๊ณ ๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค');
}
item.quantity = quantity;
}
getCart(): Cart {
const items = Array.from(this.items.values());
const total = items.reduce(
(sum, item) => sum + item.product.price * item.quantity,
0
);
return { items, total };
}
applyDiscount(discount: DiscountRule): number {
const { total } = this.getCart();
if (discount.minAmount && total < discount.minAmount) {
return total;
}
if (discount.type === 'percentage') {
return total * (1 - discount.value / 100);
} else {
return Math.max(0, total - discount.value);
}
}
clear(): void {
this.items.clear();
}
getItemCount(): number {
return Array.from(this.items.values()).reduce(
(sum, item) => sum + item.quantity,
0
);
}
}
์ด์ ์ด ์๋น์ค๋ฅผ ์๋ฒฝํ๊ฒ ํ ์คํธํด๋ณด์:
// src/cart/CartService.test.ts
import { CartService } from './CartService';
import { Product, DiscountRule } from './types';
describe('CartService', () => {
let cartService: CartService;
let sampleProducts: Product[];
beforeEach(() => {
cartService = new CartService();
sampleProducts = [
{ id: '1', name: '๋
ธํธ๋ถ', price: 1500000, stock: 10 },
{ id: '2', name: '๋ง์ฐ์ค', price: 30000, stock: 50 },
{ id: '3', name: 'ํค๋ณด๋', price: 80000, stock: 30 }
];
});
describe('addItem', () => {
it('์ํ์ ์ฅ๋ฐ๊ตฌ๋์ ์ถ๊ฐํ๋ค', () => {
const product = sampleProducts[0];
cartService.addItem(product, 2);
const cart = cartService.getCart();
expect(cart.items).toHaveLength(1);
expect(cart.items[0].product).toEqual(product);
expect(cart.items[0].quantity).toBe(2);
});
it('๊ฐ์ ์ํ์ ์ถ๊ฐํ๋ฉด ์๋์ด ์ฆ๊ฐํ๋ค', () => {
const product = sampleProducts[0];
cartService.addItem(product, 1);
cartService.addItem(product, 2);
const cart = cartService.getCart();
expect(cart.items).toHaveLength(1);
expect(cart.items[0].quantity).toBe(3);
});
it('0 ์ดํ์ ์๋์ผ๋ก ์ถ๊ฐํ๋ฉด ์๋ฌ๋ฅผ ๋์ง๋ค', () => {
const product = sampleProducts[0];
expect(() => cartService.addItem(product, 0)).toThrow('์๋์ 1 ์ด์์ด์ด์ผ ํฉ๋๋ค');
expect(() => cartService.addItem(product, -1)).toThrow('์๋์ 1 ์ด์์ด์ด์ผ ํฉ๋๋ค');
});
it('์ฌ๊ณ ๋ฅผ ์ด๊ณผํ๋ฉด ์๋ฌ๋ฅผ ๋์ง๋ค', () => {
const product = sampleProducts[0];
expect(() => cartService.addItem(product, 11)).toThrow('์ฌ๊ณ ๊ฐ ๋ถ์กฑํฉ๋๋ค');
});
it('๊ธฐ์กด ์๋๊ณผ ํฉ์ณ์ ์ฌ๊ณ ๋ฅผ ์ด๊ณผํ๋ฉด ์๋ฌ๋ฅผ ๋์ง๋ค', () => {
const product = sampleProducts[0];
cartService.addItem(product, 8);
expect(() => cartService.addItem(product, 3)).toThrow('์ฌ๊ณ ๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค');
});
});
describe('removeItem', () => {
it('์ฅ๋ฐ๊ตฌ๋์์ ์ํ์ ์ ๊ฑฐํ๋ค', () => {
const product = sampleProducts[0];
cartService.addItem(product, 1);
cartService.removeItem(product.id);
const cart = cartService.getCart();
expect(cart.items).toHaveLength(0);
});
it('์กด์ฌํ์ง ์๋ ์ํ ์ ๊ฑฐ ์ ์๋ฌ๋ฅผ ๋์ง๋ค', () => {
expect(() => cartService.removeItem('999')).toThrow('์ฅ๋ฐ๊ตฌ๋์ ํด๋น ์ํ์ด ์์ต๋๋ค');
});
});
describe('updateQuantity', () => {
it('์ํ ์๋์ ๋ณ๊ฒฝํ๋ค', () => {
const product = sampleProducts[0];
cartService.addItem(product, 2);
cartService.updateQuantity(product.id, 5);
const cart = cartService.getCart();
expect(cart.items[0].quantity).toBe(5);
});
it('์๋์ 0์ผ๋ก ๋ณ๊ฒฝํ๋ฉด ์ํ์ด ์ ๊ฑฐ๋๋ค', () => {
const product = sampleProducts[0];
cartService.addItem(product, 2);
cartService.updateQuantity(product.id, 0);
const cart = cartService.getCart();
expect(cart.items).toHaveLength(0);
});
it('์ฌ๊ณ ๋ฅผ ์ด๊ณผํ๋ ์๋์ผ๋ก ๋ณ๊ฒฝํ๋ฉด ์๋ฌ๋ฅผ ๋์ง๋ค', () => {
const product = sampleProducts[0];
cartService.addItem(product, 2);
expect(() => cartService.updateQuantity(product.id, 11)).toThrow('์ฌ๊ณ ๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค');
});
});
describe('getCart', () => {
it('๋น ์ฅ๋ฐ๊ตฌ๋์ ์ด์ก์ 0์ด๋ค', () => {
const cart = cartService.getCart();
expect(cart.items).toHaveLength(0);
expect(cart.total).toBe(0);
});
it('์ฅ๋ฐ๊ตฌ๋ ์ด์ก์ ์ ํํ ๊ณ์ฐํ๋ค', () => {
cartService.addItem(sampleProducts[0], 2); // 1,500,000 * 2 = 3,000,000
cartService.addItem(sampleProducts[1], 3); // 30,000 * 3 = 90,000
const cart = cartService.getCart();
expect(cart.total).toBe(3090000);
});
});
describe('applyDiscount', () => {
beforeEach(() => {
cartService.addItem(sampleProducts[0], 1); // 1,500,000์
});
it('ํผ์ผํธ ํ ์ธ์ ์ ์ฉํ๋ค', () => {
const discount: DiscountRule = { type: 'percentage', value: 10 };
const discountedTotal = cartService.applyDiscount(discount);
expect(discountedTotal).toBe(1350000); // 10% ํ ์ธ
});
it('๊ณ ์ ๊ธ์ก ํ ์ธ์ ์ ์ฉํ๋ค', () => {
const discount: DiscountRule = { type: 'fixed', value: 100000 };
const discountedTotal = cartService.applyDiscount(discount);
expect(discountedTotal).toBe(1400000);
});
it('์ต์ ๊ธ์ก ์กฐ๊ฑด์ ๋ง์กฑํ์ง ์์ผ๋ฉด ํ ์ธ์ ์ ์ฉํ์ง ์๋๋ค', () => {
const discount: DiscountRule = {
type: 'percentage',
value: 10,
minAmount: 2000000
};
const discountedTotal = cartService.applyDiscount(discount);
expect(discountedTotal).toBe(1500000); // ํ ์ธ ์์
});
it('ํ ์ธ ํ ๊ธ์ก์ด ์์๊ฐ ๋์ง ์๋๋ค', () => {
const discount: DiscountRule = { type: 'fixed', value: 2000000 };
const discountedTotal = cartService.applyDiscount(discount);
expect(discountedTotal).toBe(0);
});
});
describe('clear', () => {
it('์ฅ๋ฐ๊ตฌ๋๋ฅผ ๋น์ด๋ค', () => {
cartService.addItem(sampleProducts[0], 1);
cartService.addItem(sampleProducts[1], 2);
cartService.clear();
const cart = cartService.getCart();
expect(cart.items).toHaveLength(0);
expect(cart.total).toBe(0);
});
});
describe('getItemCount', () => {
it('์ฅ๋ฐ๊ตฌ๋์ ์ด ์ํ ๊ฐ์๋ฅผ ๋ฐํํ๋ค', () => {
cartService.addItem(sampleProducts[0], 2);
cartService.addItem(sampleProducts[1], 3);
cartService.addItem(sampleProducts[2], 1);
expect(cartService.getItemCount()).toBe(6);
});
it('๋น ์ฅ๋ฐ๊ตฌ๋์ ๊ฐ์๋ 0์ด๋ค', () => {
expect(cartService.getItemCount()).toBe(0);
});
});
describe('ํตํฉ ์๋๋ฆฌ์ค', () => {
it('์ค์ ์ผํ ์๋๋ฆฌ์ค๋ฅผ ์๋ฎฌ๋ ์ด์
ํ๋ค', () => {
// 1. ์ํ 3๊ฐ ์ถ๊ฐ
cartService.addItem(sampleProducts[0], 1);
cartService.addItem(sampleProducts[1], 2);
cartService.addItem(sampleProducts[2], 1);
// 2. ์ฅ๋ฐ๊ตฌ๋ ํ์ธ
let cart = cartService.getCart();
expect(cart.items).toHaveLength(3);
expect(cart.total).toBe(1640000);
// 3. ๋ง์ฐ์ค ์๋ ๋ณ๊ฒฝ
cartService.updateQuantity(sampleProducts[1].id, 5);
cart = cartService.getCart();
expect(cart.total).toBe(1730000);
// 4. ํ ์ธ ์ ์ฉ
const discount: DiscountRule = { type: 'percentage', value: 15 };
const finalTotal = cartService.applyDiscount(discount);
expect(finalTotal).toBe(1470500);
// 5. ํค๋ณด๋ ์ ๊ฑฐ
cartService.removeItem(sampleProducts[2].id);
cart = cartService.getCart();
expect(cart.items).toHaveLength(2);
});
});
});
์ด ํ ์คํธ๋ ๊ฑฐ์ ๋ชจ๋ ์๋๋ฆฌ์ค๋ฅผ ์ปค๋ฒํ๊ณ ์์ด. ์ ์ ์ผ์ด์ค, ์๋ฌ ์ผ์ด์ค, ์ฃ์ง ์ผ์ด์ค, ๊ทธ๋ฆฌ๊ณ ์ค์ ์ฌ์ฉ ์๋๋ฆฌ์ค๊น์ง! ์ด ์ ๋๋ฉด ํ๋ก๋์ ์ ๋ฐฐํฌํด๋ ์์ฌํ ์ ์์ด. ๐
๐ฏ ๋ง๋ฌด๋ฆฌํ๋ฉฐ
์, ์ฌ๊ธฐ๊น์ง ์ค๋๋ผ ๊ณ ์ํ์ด! ๐ ํ์ ์คํฌ๋ฆฝํธ์ Jest๋ฅผ ํ์ฉํ ํ ์คํ ์ ๋ํด ์ ๋ง ๋ง์ ๊ฑธ ๋ค๋ค์ง? ์ฒ์์ ๋ณต์กํด ๋ณด์ผ ์ ์์ง๋ง, ํ๋์ฉ ๋ฐ๋ผํ๋ค ๋ณด๋ฉด ๊ธ๋ฐฉ ์ต์ํด์ง ๊ฑฐ์ผ.
ํ ์คํธ ์ฝ๋ ์์ฑ์ ์ฒ์์ ์๊ฐ์ด ๋ ๊ฑธ๋ฆฌ๋ ๊ฒ์ฒ๋ผ ๋๊ปด์ง ์ ์์ด. ํ์ง๋ง ์ฅ๊ธฐ์ ์ผ๋ก ๋ณด๋ฉด ์์ฒญ๋ ์๊ฐ ์ ์ฝ์ด ๋ผ. ๋ฒ๊ทธ๋ฅผ ๋ฏธ๋ฆฌ ์ก๊ณ , ๋ฆฌํฉํ ๋ง์ ์์ ์๊ฒ ํ๊ณ , ์ฝ๋ ํ์ง์ ๋์ผ ์ ์๊ฑฐ๋ ! ๐ช
โ
ํ์
์คํฌ๋ฆฝํธ + Jest = ์ต๊ฐ ์กฐํฉ
ํ์
์์ ์ฑ๊ณผ ํ
์คํธ ์ปค๋ฒ๋ฆฌ์ง๋ฅผ ๋์์ ํ๋ณดํ ์ ์์ด.
โ
๋ชจํน์ ํ์
์ธ๋ถ ์์กด์ฑ์ ๋ชจํนํด์ ๋น ๋ฅด๊ณ ์์ ์ ์ธ ํ
์คํธ๋ฅผ ์์ฑํด.
โ
ํ
์คํธ๋ ๋ฌธ์๋ค
์ ์์ฑ๋ ํ
์คํธ๋ ์ฝ๋๊ฐ ์ด๋ป๊ฒ ๋์ํ๋์ง ๋ณด์ฌ์ฃผ๋ ์ต๊ณ ์ ๋ฌธ์์ผ.
โ
์ปค๋ฒ๋ฆฌ์ง๋ณด๋ค ํ์ง
100% ์ปค๋ฒ๋ฆฌ์ง๊ฐ ๋ชฉํ๊ฐ ์๋๋ผ, ์๋ฏธ ์๋ ํ
์คํธ๋ฅผ ์์ฑํ๋ ๊ฒ ๋ชฉํ์ผ.
โ
์ง์์ ์ธ ๊ฐ์
ํ
์คํธ๋ ์ฝ๋์ฒ๋ผ ๊ณ์ ๊ฐ์ ํ๊ณ ๋ฆฌํฉํ ๋งํด์ผ ํด.
โข E2E ํ ์คํธ (Playwright, Cypress)
โข ํตํฉ ํ ์คํธ ์ ๋ต
โข TDD (Test-Driven Development) ์ค์ฒ
โข ์ฑ๋ฅ ํ ์คํธ์ ๋ถํ ํ ์คํธ
โข ์๊ฐ์ ํ๊ท ํ ์คํธ
ํ ์คํธ ์์ฑ์ด ์ด๋ ต๊ฑฐ๋ ๋งํ๋ ๋ถ๋ถ์ด ์๋ค๋ฉด, ํผ์ ๊ณ ๋ฏผํ์ง ๋ง๊ณ ๋์์ ๋ฐ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ด์ผ. ๊ฒฝํ ๋ง์ ๊ฐ๋ฐ์๋ค์ ๋ ธํ์ฐ๋ฅผ ๋ฐฐ์ฐ๋ฉด ํจ์ฌ ๋น ๋ฅด๊ฒ ์ฑ์ฅํ ์ ์๊ฑฐ๋ ! ๐
์, ์ด์ ๋น์ ์ ํ๋ก์ ํธ์ ํ ์คํธ๋ฅผ ์ถ๊ฐํด๋ณผ ์๊ฐ์ด์ผ! ์์ ํจ์ ํ๋๋ถํฐ ์์ํด์ ์ ์ ํ์ฅํด๋๊ฐ๋ฉด ๋ผ. ํ์ดํ ! ๐ฅ
๋ฒ๊ทธ ์๋ ์ฝ๋๋ฅผ ํฅํด, ํจ๊ป ๋ฌ๋ ค๊ฐ์! ๐
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.