如何在 Cypress 中執行資料驅動測試?


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

Cypress fixtures 資料夾可以包含 JSON 或其他格式的檔案,資料以“鍵:值”對的形式維護。所有這些測試資料可以被多個測試使用。所有 fixture 資料都必須在 before hook 塊中宣告。

語法

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 中實現

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

實際測試的實現

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

執行結果

輸出日誌顯示值 Robert 和 789456123 分別被饋送到“全名”和“手機號碼”欄位。這些資料已從 fixture 傳遞到測試。

更新於: 2021年11月19日

283 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告