如何在赛普拉斯中重播相同的请求?

How to replay the same request in cypress?

我想测试以下用例:

  1. 我用 cy.intercept() 方法监听 POST API 请求
  2. 我点击执行POSTAPI请求的按钮
  3. 我愿意cy.wait('@myapi').its('response.statusCode').should('eq', 200);
  4. 之后我想用 cypress 再次触发请求(比如重播它)并确保这次我得到 statusCode 400 并验证响应正文以包含错误消息

如何在赛普拉斯中做到这一点?有任何想法吗? :D

我试过这样做:

    cy.intercept('POST', regexHelpers.getCartURIRegex(voucherCode)).as("redeemVoucher");

    cy.get('[data-cy="buttonRedeemVoucher"]').click();

    // cy.wait('@redeemVoucher').its('response.statusCode').should('eq', 200);
    cy.wait('@redeemVoucher').then(function(interception) {
      expect(interception.response.statusCode).to.eq(200);
      const url = interception.request.url;
       cy.request({
         method: 'POST',
         url: url,
         headers: {
          'Content-Type': 'application/json; charset=utf-8'
       }}).its('status').should('eq', 400);
    }); 

但在这种情况下,我得到 400 错误代码 - 错误的请求已经在行
expect(interception.response.statusCode).to.eq(200);

第一次调用 API 应该 return 200,但是使用相同凭证的第二次调用应该 return 400。

我很困惑为什么在这一行已经 returning 400:
expect(interception.response.statusCode).to.eq(200);

[编辑]

我成功做到了:

cy.intercept('POST', regexHelpers.getCartURIRegex(voucherCode)).as("redeemVoucher");

    cy.get('[data-cy="buttonRedeemVoucher"]').click();

    cy.wait('@redeemVoucher').its('request.url').as('voucherUrl').then(function() {
      cy.request({
        method: 'POST',
        url: this.voucherUrl,
        failOnStatusCode: false,
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        }}).its('status').should('eq', 400);
    });  

但我不知道如何在这里检查第一次呼叫响应代码是 200?
有人有想法吗? :D

您可以使用 .should(callBack)

查看第一个响应调用
cy.wait('@redeemVoucher')
  .should(interception => expect(interception.response.statusCode).to.eq(200))
  .its('request.url').as('voucherUrl').then(function() {
    cy.request({
      method: 'POST',
      url: this.voucherUrl,
      failOnStatusCode: false,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      }}).its('status').should('eq', 400);
  });  

但是您的第一个示例也可以工作,前提是您将 failOnStatusCode: false 添加到请求中。

我还做了以下也有效:

cy.wait('@redeemVoucher').should(({request, response}) => {
  expect(response.statusCode).to.eq(200);

  cy.request({
    method: 'POST',
    url: request.url,
    failOnStatusCode: false,
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }}).should((response) => {
      expect(response.status).to.eq(400);
      expect(response.body.errors[0].message).to.eq('Voucher cannot be redeemed: ' + voucherCode);
  });
});