如何在Cypress中列出并记录所有网络请求和响应时间

How to list and record all network requests and response times in Cypress

我希望将来自 cy.intercept() 的所有请求转换为 json 对象,其中包括:{'method':'____', 'url':'____', 'response_time':'____'} 以便将它们写入 json 文件以进行性能分析.

我目前能够显示所有请求方法和 URL,但不能显示它们的响应时间。

当前获取网络请求的代码:

cy.intercept({method:'GET', url:'**'}).as('gets');
cy.intercept({method:'POST', url:'**'}).as('posts');
cy.visit('url');

是否可以遍历这些单独的请求及其响应时间并将它们保存在一个数组中?

我尝试将 intercept() 返回的值保存为变量,但它没有显示所有请求或它们的响应时间。

var gets = cy.intercept({method:'GET', url:'**'}).as('gets');
var posts = cy.intercept({method:'POST', url:'**'}).as('posts');
cy.visit('url');

cy.writefile('file1.json', gets);
cy.writefile('file2.json', posts);

提前致谢。

您想使用 cy.intercept() 回调来获取持续时间。

请求回调在请求被拦截时触发,响应回调在响应returns时触发。

const gets = []

const logGet = (request) => {
  const start = Date.now()
  request.continue((response) => {
    const duration = Date.now() - start
    gets.push({url: request.url, duration})
  })
}

cy.intercept('*', logGet)

cy.intercept('**/tracking.min.js').as('done')           // last call I'm interested in

cy.visit('https://docs.cypress.io/api/commands/intercept')

cy.wait('@done').then(() => {                          // wait for last
  console.log(gets)
})

此外,选择一个标记流结束的网络请求。 Cypress 不知道调用何时结束,因此您应该在最后一个调用上 cy.wait() 而不是 wait(3000).

在上面的示例中,我选择了 Cypress 跟踪脚本。