WEB自動化-08-Cypress 接口測試

8 接口測試

    在服務和服務、系統和系統之間進行通信時,常常會使用到接口。通過接口測試,可以在項目早期更快發現問題。接口有很多類型,而現階段使用的接口是基於HTTP協議的接口。

8.1 Cypress支持的HTTP請求方式

    在Cypress中發起HTTP請求時,需要使用到的命令爲cy.request(),其基本語法格式如下所示:

cy.request(url)
cy.request(url, body)
cy.request(method, url)
cy.request(method, url, body)
cy.request(options)

    主要參數詳細信息如下所示:

  • url

    url(String),發起請求的接口地址。需要注意的事項如下所示:

    1、如果cy.request()在cy.visit()後發起請求時,則Cypress將默認使用cy.visit()中的域名做爲發起接口請求的域名地址,示例如下所示:

cy.visit('https://www.surpassme.com/app')
cy.request('users/add') //  實際訪問的URL: https://www.surpassme.com/users/add

    2、如果事先在cypress.json設置了baseUrl時,則在發送接口請求時,可以不填寫域名,Cypress在實際發起請求時,會自動將baseUrl添加到接口地址前面。示例如下所示:

// cypress.json
{
  "baseUrl": "https://www.surpassme.com/
}
cy.request('user/add') // 實際訪問的URL: https://www.surpassme.com/users/add

    3、如果Cypress沒有檢測到域名,則拋錯誤異常

  • body

    body (String, Object)是發起請求的請求體。根據接口類型,body會有不同的形式。

  • method

    method (String) 是發起請求的方法。默認請求方法爲GET,其支持的方法比較多,最常見的有GETPOSTPUTDELETE

  • **options **

    options (Object)是可選項,可以定義一些其他的參數來改變cy.request的一些行爲,主要哪下所示:

選項 默認值 功能描述
log true 是否在Command log中顯示命令
url null 發起請求的URL地址
method GET 請求方法
auth null 添加鑑權頭信息
body null 請求體
failOnStatusCode true 若返回的狀態碼不是2xx和3xx系列,則認爲請求失敗
followRedirect true 是否自動重定向
form false 是否以表單形式發送請求體,如果是的話,則設置urlencode爲x-www-form-urlencoded
encoding utf8 請求響應的編碼方式,支持ascii, base64, binary, hex, latin1, utf8, utf-8, ucs2, ucs-2, utf16le, utf-16le等
gzip true 是否接受gzip編碼
headers null 添加額外的請求頭
qs null 查詢參數,如果填寫後,則自動追加到URL地址後面
retryOnStatusCodeFailure false 在通過狀態碼判定爲失敗後的重試次數,如果設置爲true,則重試4次
retryOnNetworkFailure true 在通過網絡問題判定後爲失敗後的重試次數,如果設置true,則重試4次
timeout responseTimeout 解析域名地址的超時時間
  • 輸出內容

    在通過cy.request()發送請求後,輸出的響應內容主要有statusbodyheadersduration

8.2 示例

8.2.1 發起GET請求

    GET是平常使用最多的請求,我們來看看示例,如下所示:

/// <reference types="cypress" />

describe('發送GET請求示例', () => {
    let url="http://httpbin.org/get"

    it('發送請求的GET示例用例-1', () => {
        cy.request(url).as("response");
        cy.get("@response").should((response)=>{
            expect(response.body).to.have.property("headers")
            expect(response.body.url).to.eq(url)
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });

    it('發送請求的GET示例用例-2', () => {
        cy.request("GET",url).as("response");
        cy.get("@response").should((response)=>{
            expect(response.body).to.have.property("headers")
            expect(response.body.url).to.eq(url)
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });

    it('發送請求的GET示例用例-3', () => {
        cy.request("GET",url,{"name":"Surpass","age":28}).as("response");
        cy.get("@response").should((response)=>{
            expect(response.body).to.have.property("headers")
            expect(response.body.url).to.contain(url)
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });


    it('發送請求的GET示例用例-4', () => {
        cy.request({
            method:"GET",
            url:url,
            qs:{"name":"Surpass","age":28}
        }).then((response)=>{
           expect(response.body.args.name).to.eq("Surpass")
           expect(response.body.args.age).to.eq("28")
           expect(response.status).to.eq(200)
           expect(response.body.headers.Host).to.eq("httpbin.org")
           expect(response.body).to.have.property("headers")
        });
    });

    it('獲取圖片示例', () => {
        cy.request({
            method:"GET",
            url:"https://www.cnblogs.com/images/logo.svg",
            encoding:"base64"
        }).then((response) => {
            let base64Content=response.body;
            let mime=response.headers["content-type"];
            let imageDataUrl=`data:${mime};base64,${base64Content}`
        })
    });

    it('下載文件', () => {
      cy.request({
          method:"GET",
          url:"https://www.cnblogs.com/images/logo.svg",
          encoding:"binary"
      }).then((response)=>{
          cy.writeFile("./cnblog.logo.svg",response.body,"binary");
      })
    });
});

    運行結果如下所示:

8.2.1 發起POST請求

    示例如下所示:

/// <reference types="cypress" />

describe('發送POST請求示例', () => {
    let url="http://httpbin.org/post";
    let body={"name":"Surpass","age":28};

    it('發送請求的POST示例用例-1', () => {
        cy.request("POST",url,body).as("response");
        cy.get("@response").should((response)=>{
             expect(response.body.json.name).to.eq("Surpass")
             expect(response.body.headers.Host).to.eq("httpbin.org")
        })
    });

    it('發送請求的POST示例用例-2', () => {
        cy.request({
           method:"POST",
           url:url,
           body:body,
           form:true
        }).then((response)=>{
            expect(response.body.form.name).to.eq("Surpass")
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });

    it('發送請求的POST示例用例-3', () => {
        cy.request({
           method:"POST",
           url:url,
           body:body,
           form:false,
           headers:{"Content-Type":"application/json","Customer-Header":"Surpass"}
        }).then((response)=>{
            expect(response.body.json.name).to.contain("Surpass")
            expect(response.body.headers.Host).to.eq("httpbin.org")
            expect(response.headers["content-type"]).to.eq("application/json")
            expect(response.body.headers["Customer-Header"]).to.eq("Surpass")
        });
    });
});

    運行結果如下所示:

原文地址:https://www.jianshu.com/p/007976277dc8

本文同步在微信訂閱號上發佈,如各位小夥伴們喜歡我的文章,也可以關注我的微信訂閱號:woaitest,或掃描下面的二維碼添加關注:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章