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

使用Cypress模拟登录API不同状态码(200/400/500)遇问题求助

我帮你分析下当前的问题,然后给出能实现需求的修改方案:

你现在的测试没达到预期,核心有两个原因:一是没有在路由拦截中配置具体的状态码和响应内容,Cypress只是单纯拦截了请求但没返回任何有效响应;二是缺少触发登录请求的关键步骤(比如点击登录按钮),导致请求根本没发送出去,测试自然无法验证前端表现。

下面是调整后的完整测试代码,分三个场景分别模拟200、400、500状态码的响应:

describe('Login Component - API Mock Tests', () => {
  // 测试登录成功(200状态码)
  it('should redirect to dashboard on successful login (200 OK)', () => {
    cy.visit('/login');
    
    // 输入账号密码(模拟值即可,因为接口已被Mock)
    cy.get('#email').type('test@example.com').should('have.value', 'test@example.com');
    cy.get('#password').type('123456').should('have.value', '123456');
    
    // 拦截登录API,配置200成功响应
    cy.server();
    cy.route({
      method: 'POST',
      url: 'http://localhost:9999/api/login',
      status: 200, // 指定状态码
      response: {
        token: 'fake-jwt-token',
        user: { name: 'Test User' }
      } // 模拟后端返回的成功数据
    }).as('loginRequest'); // 给请求加别名,方便后续等待
    
    // 触发登录操作(根据你的组件调整按钮选择器)
    cy.get('button[type="submit"]').click();
    
    // 等待请求完成,确保前端处理完响应再断言
    cy.wait('@loginRequest');
    
    // 验证成功后的前端表现:跳转到仪表盘,通知显示成功
    cy.location('pathname').should('eq', '/dashboard');
    cy.get('#notification').should('contain', '登录成功');
  });

  // 测试登录参数错误(400状态码)
  it('should show error message on invalid credentials (400 Bad Request)', () => {
    cy.visit('/login');
    
    cy.get('#email').type('invalid@example.com');
    cy.get('#password').type('wrongpass');
    
    cy.server();
    cy.route({
      method: 'POST',
      url: 'http://localhost:9999/api/login',
      status: 400,
      response: {
        error: 'Invalid email or password'
      } // 模拟参数错误的返回信息
    }).as('loginRequest');
    
    cy.get('button[type="submit"]').click();
    cy.wait('@loginRequest');
    
    // 验证前端表现:停留在登录页,显示错误通知
    cy.location('pathname').should('eq', '/login');
    cy.get('#notification').should('exist').and('contain', 'Invalid email or password');
  });

  // 测试服务器错误(500状态码)
  it('should show server error message on server failure (500 Internal Server Error)', () => {
    cy.visit('/login');
    
    cy.get('#email').type('test@example.com');
    cy.get('#password').type('123456');
    
    cy.server();
    cy.route({
      method: 'POST',
      url: 'http://localhost:9999/api/login',
      status: 500,
      response: {
        error: 'Server is temporarily unavailable'
      } // 模拟服务器错误的返回信息
    }).as('loginRequest');
    
    cy.get('button[type="submit"]').click();
    cy.wait('@loginRequest');
    
    // 验证前端表现:停留在登录页,显示服务器错误通知
    cy.location('pathname').should('eq', '/login');
    cy.get('#notification').should('exist').and('contain', 'Server is temporarily unavailable');
  });
});

关键调整说明:

  • 配置响应状态与内容:在cy.route中通过status指定状态码,response返回对应的数据,这样测试详情里就会显示状态码信息(比如POST http://localhost:9999/api/login 200 Yes loginRequest)。
  • 触发登录请求:必须添加点击登录按钮的操作,否则请求不会发送,拦截逻辑也不会生效。
  • 使用别名与cy.wait:给路由添加别名后,用cy.wait等待请求完成,避免异步操作导致的断言时机问题。
  • 分场景测试:把每个状态码的测试拆成独立用例,逻辑更清晰,也方便单独调试某个场景。

如果你的Cypress版本是10+,官方推荐使用cy.intercept()替代cy.server()和cy.route(),这里给个快速示例(对应200状态):

cy.intercept('POST', 'http://localhost:9999/api/login', {
  statusCode: 200,
  body: { token: 'fake-jwt-token', user: { name: 'Test User' } }
}).as('loginRequest');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:22:34