iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0
Software Development

測試工程師的上線時間:從分析到實戰的刻意練習系列 第 11

Day 11:使用 MailSlurp 模擬郵件的收發

  • 分享至 

  • xImage
  •  

前言

我最近在看 MailSlurp 的文件,它不只是提供 Email 還有 SMS,而且可以用不同的程式語言來操作,像是 Python、Javascript、Go 等等。申請完帳號後,首頁就能看到 API access key,還有一些範例程式碼。我自己是用 TypeScript 搭配 MailSlurp Javascript Client 設定,設定好之後,按照我的慣例就會寫個測試案例,像是從郵件裡面抓出登入的驗證碼這樣。

其實,如果你用 MailSlurp 的付費帳號,還可以綁定 Gmail 或 Microsoft 這些第三方郵件服務,這樣測試起來會更彈性一點。

安裝 MailSlurp 客戶端

首先,我們得先裝 MailSlurp 的 Node.js 客戶端,這個步驟很簡單,只要跑個 npm 指令就好了:

npm install --save mailslurp-client

寫一個從郵件取得驗證碼的函式

接下來這個範例函數,會從指定的收件匣中搜尋郵件,特別是主題是「Login for Linear」的,然後用正則表達式從郵件內容中抓出登入用的驗證碼:

async function fetchVerificationCode(): Promise<string> {
    const MailSlurp = require('mailslurp-client').default;
    const apiKey = process.env.API_KEY ?? 'your-api-key';
    const mailslurp = new MailSlurp({ apiKey });

    const inboxId = 'e4d5f6de-123c-5678-0911-1234de5f62b5';
    const emails = await mailslurp.getEmails(inboxId);

    const loginEmail = emails.find((email: { subject: string; }) => email.subject === 'Login for Linear');
    if (loginEmail) {
        // 取得郵件 HTML 內容
        const emailContent = await mailslurp.getEmail(loginEmail.id);

        // 使用正則表達式取得類似 iwwti-vs3ar 的驗證碼
        const urlMatch = emailContent.body.match(/https:\/\/linear\.app\/auth\/email\/[a-zA-Z0-9@.-]+\/([a-zA-Z0-9]{10})\//);

        if (urlMatch) {
            const code = urlMatch[1];
            // 將取得的驗證碼,並輸出 iwwti-vs3ar
            const formattedCode = code.slice(0, 5) + '-' + code.slice(5);
            return formattedCode;
        } else {
            console.log('No URL or verification code found.');
        }
    } else {
        console.log('No email with subject "Login for Linear" found.');
    }
}

這個函式主要是從郵件裡抓取到的驗證碼,然後格式化成類似 iwwti-vs3ar 這樣的形式,接下來可以用在後續的流程。

用 Playwright 寫測試案例

接下來,我們用 Playwright 來寫個測試案例,讓測試流程能自動從郵件抓取驗證碼並完成登入操作:

test.describe('Login with Email should successful', () => {
    test('get started link', async ({ page }) => {

        let test_email = 'e9d7f8de@mailslurp.biz';

        // 輸入 Email
        await page.goto('https://linear.app/login');
        await page.fill('input[name="email"]', test_email);
        await page.click('button:has-text("Continue with Email")');

        // 等待寄出頁面載入完成
        await page.waitForTimeout(5000);
        await page.isVisible('button:has-text("Enter code manually")');

        // 取得郵件裡面的驗證碼
        const login_code = await fetchVerificationCode();

        // 輸入驗證馬
        await page.click('button:has-text("Enter code manually")');
        await page.fill('input[name="authToken"]', login_code);

        // 等待登入按鈕
        await page.waitForTimeout(5000);
        await page.click('button:has-text("Continue with login code")');

        // 等待進入第一次進入頁面
        await page.waitForTimeout(5000);
        assert (await page.isVisible('span:has-text("Create a new workspace")'));
    });
});

這段測試程式碼會模擬使用者在 Linear 的登入流程,並且從郵件自動抓取驗證碼來輸入。由於網路速度或者其他環境因素有時候會拖慢頁面載入速度,我在程式裡加入了幾次 waitForTimeout,確保測試可以順利進行,不會因為等待時間過短而導致測試失敗。

結論

整體來說,這篇文章展示了如何使用 MailSlurp API 搭配 Playwright,來自動化測試郵件驗證的流程。這種做法不僅可以大幅提升測試效率,還能減少手動測試的負擔。對於要處理大量驗證郵件的情境,這種方法真的很實用。


上一篇
Day 10:使用 playwright 自動化登入流程
下一篇
Day 12:測試工程師的真正價值在哪裡?
系列文
測試工程師的上線時間:從分析到實戰的刻意練習26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言