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

如何用Cypress测试邮箱OTP验证的无密码注册登录流程?

用Cypress测试无密码OTP登录/注册流程

完全可以用Cypress对这套无密码OTP流程做端到端测试,以下是具体实现步骤:

一、核心测试流程

1. 模拟用户发起OTP请求

首先访问登录页面,输入测试邮箱并触发发送OTP的操作:

cy.visit('/login');
// 假设邮箱输入框有data-testid="email-input"属性
cy.get('[data-testid="email-input"]').type('test@example.com');
// 触发发送OTP的按钮
cy.get('[data-testid="send-otp-btn"]').click();
// 等待发送成功的提示出现
cy.contains('OTP已发送至您的邮箱').should('be.visible');

2. 获取OTP验证码

推荐直接通过Supabase的Admin API获取最新的验证token,无需依赖第三方邮箱工具:
首先在cypress.config.js中配置自定义任务,用于从Supabase数据库拉取OTP:

const { defineConfig } = require('cypress');
const { createClient } = require('@supabase/supabase-js');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        async fetchSupabaseOTP(email) {
          // 用服务角色密钥初始化Supabase客户端(仅测试环境使用)
          const supabase = createClient(
            config.env.SUPABASE_URL,
            config.env.SUPABASE_SERVICE_ROLE_KEY
          );
          
          // 查询auth.verifications表,获取最新的验证token
          const { data: verification } = await supabase
            .from('auth.verifications')
            .select('token')
            .eq('email', email)
            .order('created_at', { ascending: false })
            .limit(1)
            .single();

          return verification.token;
        }
      });
    },
    // 在环境变量中配置Supabase信息
    env: {
      SUPABASE_URL: '你的测试环境Supabase地址',
      SUPABASE_SERVICE_ROLE_KEY: '你的测试环境服务角色密钥'
    }
  }
});

然后在测试用例中调用这个任务获取OTP并输入:

cy.task('fetchSupabaseOTP', 'test@example.com').then(otp => {
  // 输入OTP到验证码输入框
  cy.get('[data-testid="otp-input"]').type(otp);
});

3. 验证OTP并确认登录状态

点击验证按钮后,检查登录成功的状态:

cy.get('[data-testid="verify-otp-btn"]').click();
// 等待成功提示
cy.contains('Successfully signed in!').should('be.visible');
// 验证页面跳转
cy.url().should('include', '/dashboard');
// 检查Supabase的认证存储
cy.window().its('localStorage').invoke('getItem', 'supabase.auth.token').should('exist');

二、异常场景测试

除了正常流程,还要覆盖错误场景:

  • 错误OTP验证:
cy.get('[data-testid="otp-input"]').type('123456'); // 输入无效OTP
cy.get('[data-testid="verify-otp-btn"]').click();
// 验证错误提示
cy.contains('Invalid OTP').should('be.visible');
  • 过期OTP验证:可以先获取OTP,等待Supabase设置的OTP过期时间(默认10分钟)后再输入,验证错误提示。

三、关键注意事项

  • 必须使用独立的测试环境,避免测试操作影响生产数据或真实用户。
  • 服务角色密钥仅用于测试环境,绝对不能暴露到生产代码中。
  • 所有异步操作(比如获取OTP)要通过Cypress的task或then处理,确保流程顺序执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:21:32