You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中实现带邮箱验证的用户注册自动化测试并替代MailSlurp

Cypress 邮箱注册验证测试替代 MailSlurp 方案

以下是两种无额度压力的可行实现方案,适配你提出的测试用例需求:

方案1:Mailosaur 对接(中小项目友好)

使用cypress-mailosaur插件对接 Mailosaur 测试邮件服务,免费版单月支持100封测试邮件,额度比MailSlurp基础版宽松,操作逻辑与MailSlurp高度一致,迁移成本极低。

方案2:Ethereal Email 对接(完全免费,无额度限制)

Ethereal 是专门面向自动化测试场景的临时邮箱服务,所有邮件仅存于服务端不会外发,无需注册即可使用,适合全量自动化测试场景。

具体实现步骤

  1. 安装依赖包
npm install nodemailer imapflow cypress-wait-until --save-dev
  1. 在cypress/support/commands.js中添加自定义命令
// 生成随机临时邮箱账号
Cypress.Commands.add('createRandomEmail', () => {
  return cy.request('POST', 'https://api.nodemailer.com/user', {
    requestor: 'cypress-test'
  }).then(res => {
    return {
      email: res.body.user,
      pass: res.body.pass
    }
  })
})

// 提取激活链接
Cypress.Commands.add('getActivationLink', (emailCreds) => {
  return cy.task('fetchLatestEmail', emailCreds).then(emailContent => {
    return emailContent.match(/https?:\/\/[^\s"]+\/activate[^\s"]+/)[0]
  })
})
  1. 在cypress.config.js中配置收信节点任务
const { defineConfig } = require('cypress')
const { ImapFlow } = require('imapflow')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        async fetchLatestEmail(emailCreds) {
          const client = new ImapFlow({
            host: 'imap.ethereal.email',
            port: 993,
            secure: true,
            auth: {
              user: emailCreds.email,
              pass: emailCreds.pass
            }
          })
          await client.connect()
          const lock = await client.getMailboxLock('INBOX')
          try {
            const latestEmail = await client.fetchOne('*', { source: true })
            return latestEmail.source.toString()
          } finally {
            lock.release()
            await client.logout()
          }
        }
      })
    }
  }
})
  1. 编写测试用例
describe('用户注册流程测试', () => {
  it('随机邮箱注册并完成账号激活', () => {
    // 步骤1:生成随机邮箱完成注册
    cy.createRandomEmail().then(emailInfo => {
      cy.visit('/register')
      cy.get('input[name="email"]').type(emailInfo.email)
      cy.get('input[name="password"]').type('Test@pass123')
      cy.get('button[type="submit"]').click()
      cy.contains('验证邮件已发送').should('be.visible')

      // 步骤2:接收邮件点击激活链接
      cy.waitUntil(() => cy.getActivationLink(emailInfo), {
        timeout: 30000,
        interval: 2000
      }).then(activationLink => {
        cy.visit(activationLink)
        cy.contains('账号激活成功').should('be.visible')
      })
    })
  })
})

补充说明

如果需要测试真实邮件外发逻辑,可将上述配置中的IMAP服务替换为自有域名下的企业邮箱IMAP接口,完全无额度限制。本地单元测试场景也可直接Mock邮件服务,从后端接口直接获取激活链接跳过收信步骤,提升测试执行效率。

内容的提问来源于stack exchange,提问作者Piotr Franczak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:15:02