Cypress - Fixture(夾具)


Cypress fixtures 用於維護和儲存自動化測試的資料。fixtures 位於 Cypress 專案的 fixtures 資料夾中(例如 example.json 檔案)。基本上,它幫助我們從外部檔案獲取資料輸入。

Features

Cypress fixtures 資料夾可以包含 JSON 或其他格式的檔案,資料以“鍵值對”的形式維護。

所有測試資料可以被多個測試使用。所有 fixture 資料都必須在 before 鉤子塊內宣告。

語法

Cypress 資料驅動測試的語法如下:

cy.fixture(path of test data)
cy.fixture(path of test data, encoding type)
cy.fixture(path of test data, opts)
cy.fixture(path of test data, encoding type, options)

這裡:

  • 測試資料路徑 是 fixtures 資料夾內測試資料檔案的路徑。

  • 編碼型別 - 編碼型別(utf-8、asci 等)用於讀取檔案。

  • Opts - 修改響應的超時時間。預設值為 30000ms。在 cy.fixture() 之前等待時間會丟擲異常。

在 example.json 中的實現

以下是使用 Cypress 中的 example.json 進行資料驅動測試的實現:

{
   "fullName": "Robert",
   "number": "789456123"
}

實際測試的實現

在 Cypress 中實際資料驅動測試的實現如下:

describe('Tutorialspoint Test', function () {
   //part of before hook
   before(function(){
      //access fixture data
      cy.fixture('example').then(function(regdata){
         this.regdata=regdata
      })
   })
   // test case
   it('Test Case1', function (){
      // launch URL
      cy.visit("https://register.rediff.com/register/register.php")
      //data driven from fixture
      cy.get(':nth-child(3) > [width="185"] > input')
      .type(this.regdata.fullName)
      cy.get('#mobno').type(this.regdata.number)
   });
});

執行結果

輸出如下:

Data Driven Testing in Cypress

輸出日誌顯示值 Robert 和 789456123 分別被輸入到“全名”和“手機號碼”欄位中。這些資料是從 fixtures 傳遞到測試中的。

廣告
© . All rights reserved.