赛普拉斯-在click()之后记录来自请求的响应数据 [英] Cypress - log response data from an request after a click()

查看:282
本文介绍了赛普拉斯-在click()之后记录来自请求的响应数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我知道这可能不是最佳实践,但是我想要实现的是在整个UI中创建记录后,从数据库中静默删除记录。以这种方式,我想保持我们的测试环境尽可能清晰,并减少测试数据的噪音。

Although I know this may not be considered as a best practice, but what I want to achieve is to silently delete a record from a database after the same was created throughout UI. In htat way I want to keep our test environment clear as much as possible and reduce the noise of test data.

我的测试通过单击UI创建新记录后,我等待POST请求完成,然后从响应中提取ID(因此,可以通过调用 cy.request('DELETE','/ id'))重用它以静默方式删除该记录。

After my tests create a new record by clicking over the UI, I wait for POST request to finish and then I would like to extract the id from the response (so I can reuse it to silently delete that record by calling the cy.request('DELETE', '/id')).

这是我作为展示柜进行的样本测试。我想知道为什么在此示例中什么都没记录。

Here's a sample test I have put on as a showcase. I'm wondering why nothing is logged in this example.

it('GET cypress and log', () => {
  cy.server()
    .route('**/repos/cypress-io/cypress*')
    .as('getSiteInfo');

  cy.visit('https://www.cypress.io/dashboard');

  cy.get('img[alt="Cypress.io"]')
    .click()
    .wait('@getSiteInfo')
    .then((response) => {
      cy.log(response.body)
    })
})

据我从此处看到的 https://docs.cypress.io/api/commands/wait.html#Alias 这应该没问题。

As far as I can see from here https://docs.cypress.io/api/commands/wait.html#Alias this should be fine.

推荐答案

您的代码包含两个问题。

your code contains two problems.

第一个
点击触发新页面的加载,但是cypress不会等到 PageLoad 事件引发(因为您没有使用 visit )。在我的PC上,该请求大约需要5秒钟,直到点击之后被触发。因此,您应该使用 wait(...,{超时:10000})

First: The click triggers a new page to be loaded but cypress does not wait until the PageLoad event is raised (because you do not use visit). On my PC the Request takes about 5 seconds until it is triggered after the click. So you should use wait(..., { timeout: 10000 }).

第二:
wait()产生XHR对象,而不是响应。因此,然后内的代码不正确。身体也作为对象传递。因此,您应该使用 JSON.stringify()在命令日志中查看结果。

Second: wait() yields the XHR object, not the response. So your code within then is not correct. Also the body is passed as object. So you should use JSON.stringify() to see the result in the command log.

此代码有效:

describe("asda", () => {
    it('GET cypress and log', () => {
        cy.server()
          .route('**/repos/cypress-io/cypress*')
          .as('getSiteInfo');

        cy.visit('https://www.cypress.io/dashboard');

        cy  
          .get('img[alt="Cypress.io"]')
          .click()
          .wait('@getSiteInfo', { timeout: 20000 })
          .then((xhr) => {
            cy.log(JSON.stringify(xhr.response.body))
          })
      })
})

这篇关于赛普拉斯-在click()之后记录来自请求的响应数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆