Skip to content

Commit 92f6088

Browse files
authored
Update main_test.js
1 parent f02be33 commit 92f6088

File tree

1 file changed

+36
-25
lines changed

1 file changed

+36
-25
lines changed

lab2/main_test.js

+36-25
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,46 @@ const test = require('node:test');
22
const assert = require('assert');
33
const { Application, MailSystem } = require('./main');
44

5-
// Stub: Stub是一個假的相依物件,用來替換真正的相依物件
6-
const mailSystemStub = {
7-
sendMail: () => {} // Stub了sendMail方法
8-
};
5+
test('Application sends email when invoked', () => {
6+
// Stub: 使用 Stub 來模擬 MailSystem 的行為
7+
const mailSystemStub = {
8+
sendMail: jest.fn()
9+
};
10+
11+
const app = new Application(mailSystemStub);
12+
app.sendEmail();
913

10-
// Mock: Mock是一個模擬的相依物件,用來驗證被測試程式的交互作用
11-
const mailSystemMock = {
12-
sendMail: jest.fn() // 使用Jest的Mock函數來模擬sendMail方法
13-
};
14+
// 驗證 sendMail 方法被調用
15+
expect(mailSystemStub.sendMail).toHaveBeenCalled();
16+
});
1417

15-
// Spy: Spy是一種監視函數的調用情況,用來驗證函數是否被正確調用
16-
const mailSystemSpy = jest.spyOn(mailSystem, 'sendMail');
18+
test('Application does not send email when disabled', () => {
19+
// Mock: 使用 Mock 來模擬 MailSystem 的行為
20+
const mailSystemMock = {
21+
sendMail: jest.fn()
22+
};
1723

18-
test('Application sends email when invoked', () => {
19-
const app = new Application(mailSystemStub); // 使用Stub來注入假的相依物件
20-
app.sendEmail(); // 觸發應用程式的發送郵件操作
21-
// 在這裡進行斷言,驗證是否正確調用了假的相依物件的sendMail方法
22-
});
24+
const app = new Application(mailSystemMock);
25+
app.disableEmail();
26+
app.sendEmail();
2327

24-
test('Application sends email when invoked - using mock', () => {
25-
const app = new Application(mailSystemMock); // 使用Mock來注入模擬的相依物件
26-
app.sendEmail(); // 觸發應用程式的發送郵件操作
27-
// 在這裡進行斷言,驗證是否正確調用了模擬的相依物件的sendMail方法
28-
expect(mailSystemMock.sendMail).toHaveBeenCalled(); // 驗證sendMail方法是否被呼叫
28+
// 驗證 sendMail 方法未被調用
29+
expect(mailSystemMock.sendMail).not.toHaveBeenCalled();
2930
});
3031

31-
test('Application sends email when invoked - using spy', () => {
32-
const app = new Application(mailSystem); // 直接使用真實的相依物件
33-
app.sendEmail(); // 觸發應用程式的發送郵件操作
34-
// 在這裡進行斷言,驗證是否正確調用了真實的相依物件的sendMail方法
35-
expect(mailSystemSpy).toHaveBeenCalled(); // 使用Spy來驗證sendMail方法是否被呼叫
32+
test('Application retries sending email on failure', () => {
33+
// Spy: 使用 Spy 來監視 MailSystem 的行為
34+
const mailSystemSpy = jest.spyOn(MailSystem.prototype, 'sendMail');
35+
36+
const app = new Application(new MailSystem());
37+
app.sendEmail();
38+
39+
// 模擬 sendMail 失敗
40+
mailSystemSpy.mockImplementationOnce(() => { throw new Error('Failed to send email'); });
41+
42+
// 再次調用 sendEmail 方法,應該會進行重試
43+
app.sendEmail();
44+
45+
// 驗證 sendMail 方法被調用了兩次
46+
expect(mailSystemSpy).toHaveBeenCalledTimes(2);
3647
});

0 commit comments

Comments
 (0)