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

Cypress如何在不同浏览器中执行特定认证测试用例?

实现Cypress同一测试流程跨浏览器执行认证场景

Cypress默认单测试进程仅支持绑定一个浏览器,无法在单个测试实例中切换浏览器。要实现你需要的跨浏览器串联流程,可通过拆分测试步骤+共享测试状态+启动多浏览器实例的方式完成,具体方案如下:

核心思路

将你的认证流程拆分为两个关联的测试阶段,通过外部存储共享状态,分别在Chrome和Firefox中执行,最终串联成完整流程:

  1. Chrome端完成登录+后续操作,标记状态为完成
  2. Firefox端监听状态完成信号,触发登录并完成OTP验证

步骤1:配置状态共享机制

通过Cypress的task能力实现本地文件读写,用于存储跨浏览器的状态标记。在cypress.config.ts中添加如下配置:

import { defineConfig } from 'cypress';
import * as fs from 'fs';

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        // 写入测试状态
        writeTestState: (state) => {
          const statePath = './cypress/fixtures/test-state.json';
          fs.writeFileSync(statePath, JSON.stringify(state));
          return null;
        },
        // 读取测试状态
        readTestState: () => {
          const statePath = './cypress/fixtures/test-state.json';
          if (fs.existsSync(statePath)) {
            return JSON.parse(fs.readFileSync(statePath, 'utf8'));
          }
          return null;
        },
        // 清理测试状态
        deleteTestState: () => {
          const statePath = './cypress/fixtures/test-state.json';
          if (fs.existsSync(statePath)) fs.unlinkSync(statePath);
          return null;
        }
      });
    },
  },
});

步骤2:编写跨浏览器测试代码

在authentication.cy.ts中编写分浏览器执行的测试逻辑:

describe('跨浏览器认证流程', () => {
  before(() => {
    // 测试前清理状态文件,避免残留影响
    cy.task('deleteTestState');
  });

  it('Chrome端:登录并完成前置操作', () => {
    // 仅在Chrome环境执行
    if (!Cypress.isBrowser('chrome')) return;

    // 1. Chrome中完成登录
    cy.visit('/login');
    cy.get('[data-testid="username"]').type('test-user');
    cy.get('[data-testid="password"]').type('test-pass');
    cy.get('[data-testid="submit-login"]').click();
    cy.get('[data-testid="user-profile"]').should('be.visible');

    // 2. 执行登录后的若干操作(示例:修改个人资料)
    cy.visit('/profile');
    cy.get('[data-testid="edit-profile"]').click();
    cy.get('[data-testid="bio"]').type('跨浏览器测试示例');
    cy.get('[data-testid="save-profile"]').click();
    cy.get('[data-testid="success-alert"]').should('be.visible');

    // 标记Chrome操作完成,写入状态文件
    cy.task('writeTestState', { userId: 'test-user', chromeLoginCompleted: true });
  });

  it('Firefox端:触发登录并完成OTP验证', () => {
    // 仅在Firefox环境执行
    if (!Cypress.isBrowser('firefox')) return;

    // 轮询等待Chrome端完成操作
    const waitForChromeReady = () => {
      cy.task('readTestState').then((state) => {
        if (state?.chromeLoginCompleted) return;
        cy.wait(2000);
        waitForChromeReady();
      });
    };
    waitForChromeReady();

    // 3. Firefox中尝试登录
    cy.visit('/login');
    cy.get('[data-testid="username"]').type('test-user');
    cy.get('[data-testid="password"]').type('test-pass');
    cy.get('[data-testid="submit-login"]').click();

    // 4. 等待OTP输入框出现(确认触发邮件发送)
    cy.get('[data-testid="otp-input"]').should('be.visible');

    // 获取OTP(替换为你的实际逻辑:如调用后端接口/解析邮件)
    cy.request('GET', '/api/get-otp?user=test-user').then((res) => {
      const otp = res.body.otp;

      // 5. 输入OTP完成登录
      cy.get('[data-testid="otp-input"]').type(otp);
      cy.get('[data-testid="submit-otp"]').click();
      cy.get('[data-testid="user-profile"]').should('be.visible');
    });
  });
});

步骤3:启动多浏览器测试

打开两个终端,分别启动对应浏览器的测试实例:

  1. Chrome端测试:
npx cypress run --browser chrome --spec cypress/e2e/authentication.cy.ts
  1. Firefox端测试:
npx cypress run --browser firefox --spec cypress/e2e/authentication.cy.ts

也可在package.json中配置脚本,一键启动两个测试:

{
  "scripts": {
    "test:chrome": "cypress run --browser chrome --spec cypress/e2e/authentication.cy.ts",
    "test:firefox": "cypress run --browser firefox --spec cypress/e2e/authentication.cy.ts",
    "test:cross-browser": "npm run test:chrome & npm run test:firefox"
  }
}

执行npm run test:cross-browser即可同时启动两个浏览器的测试流程。

补充说明

  • 状态共享:CI环境中可替换为Redis等分布式缓存,避免本地文件依赖
  • OTP获取:若无法通过接口获取,可使用Mailosaur等邮件测试工具解析邮件内容
  • 执行顺序:若需严格保证Chrome测试先完成,可在Firefox测试中增加超时机制,避免无限等待

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:10:31