首页 > 解决方案 > 我可以登录以归档在运行 cypress 测试期间做出的所有响应吗?

问题描述

当我运行 cypress e2e 测试时,应用程序会发出 XHR 请求。如何记录所有这些请求和响应?我不想存根这些请求。我将获得一个包含测试期间提出的所有请求和响应的工件。Gitlab 用作 CI。

主要测试代码如下所示。所有这些都是用户定义的命令,与应用程序交互。与应用程序交互会导致发出不同的请求(例如,我单击一个按钮,这会导致请求)。

it('Log response to a file',function(){
      cy.request({
          method: 'GET',
          url: 'https://<site>/home/payments/currency/confirm/*',
          headers: {
              'Content-Type': 'application/json',
          },
          body: {},
      }).then((response)=>{
      const someResponse =  response.body;
      console.log("hhhh"+someResponse);
      cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
      cy.login(login_name, pass)
      cy.typeOTPpinpad(secret)
      cy.makePayment('Currency', 'amount')
      cy.typeToken(secret)
      cy.logout()
})
})



这是我尝试使用正则表达式捕获请求的方式(id 是唯一的,我需要使用正则表达式)。

https://<mysite>/home/payments/<currency>/confirm/* - asterisk is payment id.

标签: cypress

解决方案


您可以抓住requestandresponse并写入如下位置。我已将请求和响应写入fixture文件夹,如下所示:尝试以下内容并告诉我

it('Log request to a file',function(){
        cy.request({
            method: 'GET',
            url: 'url_here',
            headers: {
                'Content-Type': 'application/json',
            },
            body: {},
        }).then((request)=>{
        const someRequest =  JSON.stringify(request);
        console.log("hhhh"+someRequest);
        cy.writeFile('cypress/fixtures/testRequest.json', someRequest);
        })
    })

// 以下是响应:

it('Log response to a file',function(){
        cy.request({
            method: 'GET',
            url: 'url_here',
            headers: {
                'Content-Type': 'application/json',
            },
            body: {},
        }).then((response)=>{
        const someResponse =  response.body;
        console.log("hhhh"+someResponse);
        cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
        })
    })

推荐阅读