1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
| // Jest를 사용한 테스트 예시
const { jest } = require('@jest/globals');
// 테스트할 실제 클래스
class UserService {
constructor(database) {
this.database = database;
}
async getUserById(id) {
const user = await this.database.findUser(id);
if (!user) {
throw new Error('User not found');
}
return user;
}
async updateUserEmail(id, newEmail) {
const user = await this.database.findUser(id);
if (!user) {
throw new Error('User not found');
}
user.email = newEmail;
await this.database.updateUser(id, user);
return user;
}
}
// Stub 예시
class DatabaseStub {
constructor() {
this.users = new Map([
[1, { id: 1, name: 'John Doe', email: 'john@example.com' }],
[2, { id: 2, name: 'Jane Doe', email: 'jane@example.com' }]
]);
}
async findUser(id) {
return this.users.get(id);
}
async updateUser(id, userData) {
this.users.set(id, userData);
return userData;
}
}
// 테스트 코드
describe('UserService', () => {
// Stub을 사용한 테스트
describe('with stub', () => {
const dbStub = new DatabaseStub();
const userService = new UserService(dbStub);
test('should return user when exists', async () => {
const user = await userService.getUserById(1);
expect(user.name).toBe('John Doe');
});
test('should throw error when user not found', async () => {
await expect(userService.getUserById(999))
.rejects
.toThrow('User not found');
});
});
});
|