Mailtr
← Blog

Cypress: tự động lấy mã xác minh email khi test đăng ký

Cypress chạy trong trình duyệt nên gọi API ngoài (lấy OTP) nên đặt trong cy.task ở tầng Node. Mẫu dưới đây cho bạn một task tạo inbox và chờ OTP.

Bước 1: Khai báo task trong cypress.config

Thêm hai task createInbox và waitForOtp gọi Mailtr API:

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

module.exports = {
  e2e: {
    setupNodeEvents(on) {
      on("task", {
        async createInbox() {
          const r = await fetch(BASE + "/api/v1/inbox", { method: "POST", headers: H, body: "{}" });
          return r.json();
        },
        async waitForOtp(inboxId) {
          const end = Date.now() + 60000, seen = new Set();
          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 && full.message.otp) return full.message.otp;
            }
            await new Promise((r) => setTimeout(r, 3000));
          }
          throw new Error("OTP timeout");
        },
      });
    },
  },
};

Bước 2: Dùng trong test

Lấy inbox, điền vào form, rồi nhập OTP nhận được:

it("dang ky + xac minh OTP", () => {
  cy.task("createInbox").then((inbox) => {
    cy.visit("https://app-cua-ban.com/register");
    cy.get("#email").type(inbox.address);
    cy.contains("button", "Dang ky").click();
    cy.task("waitForOtp", inbox.id).then((otp) => {
      cy.get("#otp").type(otp);
      cy.contains("button", "Xac nhan").click();
      cy.contains("Dang ky thanh cong").should("be.visible");
    });
  });
});

Lưu ý

Đặt MAILTR_KEY trong biến môi trường của CI; mỗi test tạo inbox riêng để tránh nhiễu.