【问题标题】:Why is cy.intercept() causing my API request to return a 400 bad request response?为什么 cy.intercept() 导致我的 API 请求返回 400 错误请求响应?
【发布时间】:2022-01-19 00:18:04
【问题描述】:

我在 cypress 中遇到了一个问题,我的 API 请求仅在被拦截时才返回 400 错误响应。我只是使用 cy.intercept() 来监视请求,而不是操纵它。当我从测试中删除拦截命令时,请求返回 200 响应。在这两种情况下(有/没有拦截),请求标头是相同的。我还可以从截获的 400 响应中获取请求标头,并在返回 200 响应的邮递员中运行它们。 cy.intercept() 似乎只在 GET 请求上导致此问题,而不是 POST 请求。

例如。如果我这样做:

it('Should Do something', () => {   
cy.intercept('GET', '/api/rest/v2/my-featured-courses/').as('getCourses'); // declaring the GET        
cy.login();   
cy.visit('/'); 
}) 

被拦截的请求会返回 400 响应。

如果我这样做:

it('Should Do something', () => {   
cy.login();   
cy.visit('/'); 
}) 

如果没有拦截,请求会返回 200 响应。

【问题讨论】:

  • 请添加您尝试执行的代码,以及来自您的 API 的示例请求/响应。

标签: cypress http-status-code-400 intercept


【解决方案1】:

试着让它停下来。在测试开始时声明您的 GET 请求,然后执行一些操作,然后插入等待您的响应。请参阅下面的示例:

it('Should Do something', () => {
  cy.intercept('GET', '/api/rest/v2/my-featured-courses/').as('getCourses'); // declaring your GET
    
  cy.login();
  cy.visit('/');
  cy.wait('@getCourses') // using your intercepted GET

  cy.get('#Button').click();
  cy.get('.md-dialog').should('be.visible');

});

https://docs.cypress.io/api/commands/intercept#Waiting-on-a-request

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2019-12-18
    相关资源
    最近更新 更多