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

如何在Cypress中等待POST请求返回200状态码

解决Cypress测试中等待POST请求返回200的问题

要实现等待POST请求返回200后再执行后续测试步骤,核心是用Cypress的cy.intercept()监听目标请求,再通过cy.wait()等待请求完成并验证状态码。具体操作如下:

1. 拦截目标POST请求

在点击触发请求的按钮前,先定义对该POST请求的拦截,并给它设置一个别名(比如@createResponse)。你需要把示例中的接口路径替换成实际触发的POST请求URL,也可以用正则匹配部分路径:

// 替换为你的实际POST接口路径,例如 '/api/responses/create'
cy.intercept('POST', '/your-post-endpoint').as('createResponse');

2. 等待请求返回200

点击触发请求的按钮后,调用cy.wait()等待刚才拦截的请求,同时验证其响应状态码为200:

cy.get('[data-cy="testing"]').should('exist').click({ force: true });
// 等待POST请求完成并验证状态码
cy.wait('@createResponse').its('response.statusCode').should('eq', 200);

修改后的完整测试代码

把上述逻辑整合到你的测试代码中,最终代码如下:

describe("E2E CognitiveTool", function () {
  it("should crear respuesta simple sin problemas", function () {
    cy.visit("http://localhost:3000");
    cy.contains('[data-cy="topicName"]', 'CA2');
    cy.get('[data-cy="accederResponsesCA2"]').click();
    cy.get('[data-cy="crearResponse"]').should('exist').click();
    
    cy.get('input[name="description"]').type('Simple Cypres Response');
    cy.get('[name="typeResponse"]').first().check({ force: true });
    cy.get('[name="lateral_W"]').first().check({ force: true });
    cy.get('[name="rolViews"]').first().check({ force: true });
    cy.get('[name="workLoadLevel"]').first().check({ force: true });
    cy.get('[data-cy="continuar"]').click();
    
    cy.get('input[id=0]').type('hola');
    cy.get('input[id=1]').type('adios');
    cy.get('input[id=2]').type('cypress');
    cy.get('input[id=3]').type('jest');
    cy.get('input[id=4]').type('testing');
    cy.get('input[id=5]').type('automatico');

    // 拦截目标POST请求
    cy.intercept('POST', '/your-post-endpoint').as('createResponse'); // 替换为实际接口路径
    
    cy.get('[data-cy="testing"]').should('exist').click({ force: true });
    
    // 等待请求返回200
    cy.wait('@createResponse').its('response.statusCode').should('eq', 200);

    // 后续步骤将在请求完成后执行
    cy.window().its('open').should('exist');
    cy.get('[data-cy="continuar"]').click();
    
    cy.get('input[name="title"]').type('Titulo de respuesta simple');
    cy.get('input[name="text"]').type('TEXTO DE CYPRESS de respuesta simple');
    cy.get('[data-cy="saveandedit"]').should('exist').click();
  });
});

注意事项

  • 若不确定POST请求的具体URL,可打开Cypress Test Runner的Network面板,点击按钮触发请求后查看对应地址。
  • 可以用正则表达式匹配接口路径,比如接口是/api/v1/responses/create,可写成cy.intercept('POST', /api\/v1\/responses/).as('createResponse'),适配更灵活。
  • 确保拦截的请求方法(POST)与实际请求一致,否则cy.wait()会超时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:07:52