Mailtr
← Blog

Test luồng đăng ký + OTP bằng Playwright và Mailtr

Khi test luồng đăng ký có bước xác minh email/OTP, bạn cần một địa chỉ email thật nhận được thư trong lúc test chạy. Mailtr API giải quyết việc đó: tạo inbox, lấy địa chỉ điền vào form, rồi đọc OTP tự động.

Bước 1: Helper gọi Mailtr

Tạo một helper nhỏ tạo inbox và chờ OTP (TypeScript):

// mailtr.ts
const BASE = "https://mailtr.vn";
const KEY = process.env.MAILTR_KEY!;
const H = { "X-API-Key": KEY, "content-type": "application/json" };

export async function createInbox() {
  const r = await fetch(BASE + "/api/v1/inbox", { method: "POST", headers: H, body: "{}" });
  return (await r.json()) as { id: string; address: string };
}

export async function waitForOtp(inboxId: string, timeoutMs = 60000) {
  const end = Date.now() + timeoutMs;
  const seen = new Set<string>();
  while (Date.now() < end) {
    const list = await (await fetch(BASE + "/api/v1/inbox/" + inboxId + "/messages", { headers: H })).json();
    for (const m of list.messages ?? []) {
      if (seen.has(m.id)) continue;
      seen.add(m.id);
      const full = await (await fetch(BASE + "/api/v1/messages/" + m.id, { headers: H })).json();
      if (full.message?.otp) return full.message.otp as string;
    }
    await new Promise((r) => setTimeout(r, 3000));
  }
  throw new Error("Hết thời gian chờ OTP");
}

Bước 2: Test Playwright

Dùng helper trong test: điền địa chỉ tạm vào form đăng ký, lấy OTP và nhập:

import { test, expect } from "@playwright/test";
import { createInbox, waitForOtp } from "./mailtr";

test("đăng ký + xác minh OTP", async ({ page }) => {
  const inbox = await createInbox();

  await page.goto("https://app-cua-ban.com/register");
  await page.getByLabel("Email").fill(inbox.address);
  await page.getByRole("button", { name: "Đăng ký" }).click();

  const otp = await waitForOtp(inbox.id);
  await page.getByLabel("Mã xác minh").fill(otp);
  await page.getByRole("button", { name: "Xác nhận" }).click();

  await expect(page.getByText("Đăng ký thành công")).toBeVisible();
});

Lưu ý

Đặt MAILTR_KEY trong biến môi trường của CI. Mỗi test nên tạo inbox riêng để tránh nhiễu. Khi chạy nhiều test song song, chú ý quota gói — nâng gói nếu cần.