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

使用Cypress测试React-Admin+Firebase认证时出现跨域错误,登录后返回登录页面的解决方案求助

解决react-admin-firebase + Cypress登录测试跨域问题的几种方案

我之前也碰到过类似的react-admin结合Firebase认证的Cypress测试跨域坑,给你几个亲测可行的思路试试:

1. 绕过前端登录,直接模拟Firebase认证状态

react-admin-firebase是基于Firebase Auth状态来识别用户的,我们完全可以跳过前端登录UI,直接通过Firebase的认证接口获取token后,手动写入浏览器的localStorage,让应用认为用户已经登录。这种方法最高效,也从根源上避免了跨域问题。

示例代码:

describe('Authenticated routes', () => {
  beforeEach(() => {
    // 调用Firebase官方的密码登录接口获取认证信息
    cy.request({
      method: 'POST',
      url: 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=YOUR_FIREBASE_API_KEY',
      body: {
        email: '你的测试账号邮箱',
        password: '测试账号密码',
        returnSecureToken: true
      }
    }).then((response) => {
      // 将认证信息存入localStorage,react-admin-firebase会自动读取这个状态
      const authUser = JSON.stringify({
        uid: response.data.localId,
        email: response.data.email,
        stsTokenManager: {
          accessToken: response.data.idToken,
          expirationTime: Date.now() + parseInt(response.data.expiresIn) * 1000,
          refreshToken: response.data.refreshToken
        },
        providerData: []
      });
      window.localStorage.setItem('firebase:authUser:YOUR_FIREBASE_API_KEY:[DEFAULT]', authUser);
    });

    // 直接进入目标页面,无需走登录流程
    cy.visit('/#/users');
  });

  it('should access users page successfully', () => {
    cy.url().should('include', '/users');
    // 这里可以添加更多页面元素的断言,比如用户列表是否加载
  });
});

注意替换代码中的YOUR_FIREBASE_API_KEY为你项目的实际API密钥,测试账号需要提前在Firebase控制台创建好。

2. 拦截Google API请求,模拟成功响应

如果你一定要保留前端登录的UI流程,可以用Cypress的cy.intercept拦截Firebase调用的Google认证接口,直接返回模拟的成功响应,避免实际请求触发跨域。

示例代码:

describe('Login page', () => { 
  beforeEach(() => {
    // 拦截Firebase的密码登录请求
    cy.intercept('POST', 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword*', {
      statusCode: 200,
      body: {
        localId: 'test-user-uid',
        email: 'login@example.com',
        idToken: 'fake-valid-token',
        expiresIn: '3600',
        refreshToken: 'fake-refresh-token'
      }
    }).as('signInRequest');
  });

  it('Logged in successfully with login and password', () => { 
    cy.visit('http://localhost:3000');
    cy.get('input#username').type('login');
    cy.get('input#password').type('password');
    cy.get('button').contains('Sign in').click();
    
    // 等待拦截的请求完成
    cy.wait('@signInRequest');
    
    // 验证是否成功跳转到用户页面
    cy.url().should('include', '/users');
  }) 
})

这个方法能保留完整的登录UI测试流程,但需要确保模拟的响应结构符合Firebase的返回格式,否则react-admin-firebase可能无法识别登录状态。

3. 排查chromeWebSecurity: false不生效的问题

如果坚持想用关闭跨域安全的方式,先检查你的Cypress配置是否正确:

  • 确保配置写在最新版的cypress.config.js中(旧版的cypress.json已经不再推荐):
const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    chromeWebSecurity: false,
    // 其他配置项...
  },
});
  • 确认你是用Chrome浏览器运行测试,这个配置只对Chrome内核的浏览器生效,Firefox等其他浏览器不支持该设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 17:07:45