Cypress - 獲取和傳送請求


GET 和 POST 方法是應用程式程式設計介面 (API) 測試的一部分,Cypress 可以執行此測試。

GET 方法

要執行 GET 操作,我們將使用 cy.request() 發出 HTTP 請求,並將方法 GET 和 URL 作為引數傳遞給該方法。

狀態碼反映請求是否已正確接受和處理。程式碼 200(表示成功)和 201(表示已建立)。

GET 方法的實現

以下是 Cypress 中 GET 方法的實現:

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')
      });
   })
})

執行結果

輸出如下:

Get Method

POST 方法

使用 POST 方法時,我們實際上是在傳送資訊。如果我們有一組實體,我們可以使用 POST 在末尾追加新的實體。

要執行 POST 操作,我們將使用 cy.request() 發出 HTTP 請求,並將方法 POST 和 URL 作為引數傳遞給該方法。

POST 方法的實現

以下是 Cypress 中 POST 方法的實現:

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',
      })
   })
});

執行結果

輸出如下:

Post Method
廣告