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

如何在Cypress中实现Firebase认证测试?寻求REST API替代方案

在Cypress中实现Firebase认证的替代方案

针对你提到的使用REST API实现Firebase认证的需求,以下几种替代方案更适合Cypress测试场景:

方案一:Firebase Admin SDK + Cypress自定义任务

利用Cypress的Node环境任务,结合Firebase Admin SDK生成认证令牌,避免前端跨域问题,同时支持复杂的用户管理操作。

步骤:

  1. 安装依赖:
npm install firebase-admin --save-dev
  1. 在cypress.config.js中配置任务与Admin SDK初始化:
const { defineConfig } = require('cypress')
const admin = require('firebase-admin');

// 导入你的Firebase服务账号密钥
const serviceAccount = require('./path/to/serviceAccountKey.json');

// 初始化Admin SDK(避免重复初始化)
if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://your-firebase-project.firebaseio.com'
  });
}

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 定义生成自定义令牌的任务
      on('task', {
        async createAndAuthenticateUser(email, password) {
          // 创建新用户
          const user = await admin.auth().createUser({ email, password });
          // 生成自定义认证令牌
          const customToken = await admin.auth().createCustomToken(user.uid);
          return { user, customToken };
        },
        async getAuthTokenByEmail(email) {
          const userRecord = await admin.auth().getUserByEmail(email);
          return admin.auth().createCustomToken(userRecord.uid);
        }
      });
    },
  },
})
  1. 在测试用例中调用任务完成认证:
describe('Firebase认证测试', () => {
  it('创建新用户并验证登录状态', () => {
    cy.task('createAndAuthenticateUser', 'test-user@example.com', 'test-pass123')
      .then(({ customToken }) => {
        // 调用前端Firebase SDK的signInWithCustomToken方法完成登录
        cy.window().then(win => {
          win.firebase.auth().signInWithCustomToken(customToken)
            .then(() => {
              cy.visit('/dashboard');
              cy.get('.user-email').should('contain', 'test-user@example.com');
            });
        });
      });
  });

  it('通过已有用户邮箱获取令牌登录', () => {
    cy.task('getAuthTokenByEmail', 'existing-user@example.com')
      .then(token => {
        cy.window().then(win => win.firebase.auth().signInWithCustomToken(token));
        cy.visit('/profile');
        cy.get('.profile-name').should('be.visible');
      });
  });
});

方案二:使用cypress-firebase社区插件

这是专门为Cypress和Firebase集成设计的插件,封装了大量开箱即用的认证与数据操作命令,大幅减少代码量。

步骤:

  1. 安装依赖:
npm install cypress-firebase firebase firebase-admin --save-dev
  1. 在cypress/support/e2e.js中初始化插件:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import { attachCustomCommands } from 'cypress-firebase';

// 你的Firebase客户端配置
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
};

firebase.initializeApp(firebaseConfig);
attachCustomCommands({ Cypress, cy, firebase });
  1. 在cypress.config.js中配置插件:
const { defineConfig } = require('cypress')
const admin = require('firebase-admin');
const { plugin: cypressFirebasePlugin } = require('cypress-firebase');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 集成cypress-firebase插件
      return cypressFirebasePlugin(on, config, admin);
    },
  },
})
  1. 测试用例中使用封装好的命令:
describe('基于cypress-firebase的认证测试', () => {
  it('快速登录现有用户', () => {
    cy.login('test@example.com', 'test123');
    cy.visit('/dashboard');
    cy.get('.welcome-text').should('contain', '欢迎回来');
  });

  it('创建用户并自动登录', () => {
    cy.createUser({ email: 'new-user@example.com', password: 'new-pass123' });
    cy.visit('/profile');
    cy.get('#user-email-display').should('have.text', 'new-user@example.com');
  });

  it('通过UID直接登录', () => {
    cy.login({ uid: 'test-user-uid' });
    cy.visit('/settings');
    cy.get('.settings-panel').should('be.visible');
  });
});

方案三:直接模拟前端认证状态

如果你的WebApp登录后会在localStorage或sessionStorage中存储Firebase认证信息,可以直接在测试中设置这些值,快速模拟已登录状态。

describe('模拟已登录状态测试', () => {
  beforeEach(() => {
    cy.window().then(win => {
      // 从真实登录场景复制认证信息结构
      win.localStorage.setItem(
        'firebase:authUser:YOUR_API_KEY:[DEFAULT]',
        JSON.stringify({
          uid: 'test-uid',
          email: 'test@example.com',
          displayName: 'Test User',
          // 其他必要字段如token、expires等
        })
      );
    });
  });

  it('访问需认证的页面', () => {
    cy.visit('/dashboard');
    cy.get('.user-menu').should('be.visible');
  });
});

方案对比

  • Admin SDK + 自定义任务:灵活性最高,支持复杂的用户管理(如批量创建用户、权限设置),但需要编写更多初始化代码。
  • cypress-firebase插件:集成成本最低,封装了常用操作,适合大多数常规测试场景。
  • 直接模拟存储状态:实现最简单,但依赖前端的认证存储逻辑,一旦前端逻辑变更,测试需同步更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 13:43:24