Cypress 简明教程

Cypress - Working with XHR

XHR 是 XML HTTP Request。它是一个应用程序编程接口 (API),可用作对象,其方法在 Web 浏览器和服务器之间发送数据。XHR 中的对象可以请求以响应形式从服务器请求数据。

XHR is XML HTTP Request. It is an Application Programming Interface (API) which is available as an object, whose methods send data between a web browser and server. An object in XHR can request data from a server in the form of a response.

Cypress 不仅可以用于前端自动化,还可以通过直接访问 XHR 对象来控制网络流量。然后,它对该对象应用断言。它可以模拟或伪造响应。可以在浏览器的网络选项卡中查看 XHR 详细信息。

Cypress can not only be used for front end automation, but also can control the network traffic by directly accessing the XHR objects. Then, it applies the assertions on the objects.It can mock or stub a response. An XHR details can be seen in the Network tab in the browser.

XHR 响应头的语法如下:

XHR response Header is as follows −

xhr response header

响应如下:

The response is as follows −

response

可以使用 cy.request() 命令执行 XHR 请求。cy.intercept() 方法用于将响应重定向到匹配的请求。

To make an XHR request, the cy.request() command is used. The method cy.intercept() is used to redirect the responses to the matching requests.

Implementation of XHR request

以下命令用于解释 XHR 请求在 Cypress 中的实现——

Given below is the command to explain the implementation of XHR request in Cypress −

cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
//aliasing request
cy.get('@c').should((response) => {
   expect(response.body).to.have.length(100)
   expect(response).to.have.property('headers')
})