Cypress 简明教程

Cypress - Get and Post

Get 和 Post 方法是应用程序编程接口 (API) 测试的一部分,可由 Cypress 执行。

The Get and Post methods are a part of the Application Programming Interface (API) testing, which can be performed by Cypress.

Get Method

要执行 Get 操作,我们将用 cy.request() 发出 HTTP 请求,并将方法 Get 和 URL 作为参数传递给该方法。

To perform a Get operation, we shall make a HTTP request with the cy.request() and pass the method Get and URL as parameters to that method.

状态代码反映了请求是否已被正确接受和处理。代码 200(表示确定)和 201(表示已创建)。

The status code reflects, if the request has been accepted and handled correctly. The code 200(means ok) and 201(means created).

Implementation of Get

Get 方法在 Cypress 中的实现如下所示:

The implementation of Get method in Cypress is explained below −

describe("Get Method", function(){
   it("Scenario 2", function(){
      cy.request("GET", "https://jsonplaceholder.cypress.io/comments", {
      }).then((r) => {
         expect(r.status).to.eq(200)
         expect(r).to.have.property('headers')
         expect(r).to.have.property('duration')
      });
   })
})

Execution Results

Execution Results

输出如下 −

The output is as follows −

get method

Post Method

在使用 Post 方法时,我们实际上正在发送信息。如果我们有一组实体,借助 Post,我们可以在末尾附加新的实体。

While using the Post method, we are actually sending information. If we have a group of entities, we can append new ones at the end, with the help of Post.

为了执行一个 Post 操作,我们将使用 cy.request() 创建一个 HTTP 请求,并将方法 Post 和 URL 作为参数传递给那个方法。

To perform a Post operation, we shall make a HTTP request with the cy.request() and pass the method Post and URL as parameters to that method.

Implementation of Post

下面提供了 Post 方法在 Cypress 中的一个实现:

Given below is an implementation of Post method in Cypress −

describe("Post Method", function(){
   it("Scenario 3", function(){
      cy.request('https://jsonplaceholder.cypress.io/users?_limit=1')
      .its('body.0') // yields the first element of the returned list
      // make a new post on behalf of the user
      cy.request('POST', 'https://jsonplaceholder.cypress.io/posts', {
         title: 'Cypress',
         body: 'Automation Tool',
      })
   })
});

Execution Results

Execution Results

输出如下 −

The output is given below −

post method