使用Mocha選項執行測試



specs資料夾中的測試檔案包含describe和it塊。describe塊指的是測試套件,it塊指的是測試用例。一個describe塊可以包含多個it塊。

關於如何建立describe和it塊的詳細資訊在標題為“使用Webdriverio的正確流程”的章節中詳細討論。

為了驗證從開發團隊獲得的新版本是否健康,我們不需要執行套件中的所有測試用例。一些測試用例被識別用於冒煙/健全性測試,一旦我們有了新的版本,就會執行它們。

我們可以使用名為Grep的Mocha選項來分組測試用例並一起執行它們。為此,我們必須新增一個關鍵字,例如在it描述中使用“Smoke”。然後在執行時,我們可以指示WebdriverIO測試只觸發描述中包含“Smoke”的it塊。

讓我們以一個包含四個it塊的測試檔案為例。在這四個it塊中,有兩個it塊的描述中包含關鍵字“Smoke”。

首先,請按照標題為“使用Webdriverio的正確流程”一章中的步驟1到5操作,步驟如下:

步驟1 - 安裝NodeJS。如何在進行此安裝的詳細資訊在標題為“使用NodeJS入門”的章節中詳細說明。

步驟2 - 安裝NPM。如何在進行此安裝的詳細資訊在標題為“NPM安裝”的章節中詳細說明。

步驟3 - 安裝VS Code。如何在進行此安裝的詳細資訊在標題為“VS Code安裝”的章節中詳細說明。

步驟4 - 建立配置檔案。如何在進行此安裝的詳細資訊在標題為“配置檔案生成”的章節中詳細說明。

步驟5 - 建立一個spec檔案。如何在進行此安裝的詳細資訊在標題為“Mocha安裝”的章節中說明。

步驟6 - 在建立的Mocha spec檔案中新增以下程式碼。

//import chai library
const c = require('chai').expect
//library for parsing JSON file
const s =require('fs')
let h = JSON.parse(s.readFileSync('test/testData/test1.json'))
// test suite name
describe('Tutorialspoint application', function(){
   //iterate the test case
   h.forEach(  ({email,password})  =>{
      //test case
      it('Data Driven testing', function(){   
         // launch url
         browser.url('https://www.linkedin.com/login')  
         //identify the email field then enter key - email
         $("#username").setValue(email)
         //identify password field then enter key - password
         $("#password").setValue(password)
         //identify SSign in button then click
         $("button[type='submit']").click() 
         //verify error message
         const e = $('#error-for-password')
         console.log(e.getText() + ' - Error Text') 
         //verify Alert text with Chai assertion
         c(e.getText()).to.equal("The password must be provided.")
      });
   });
   // it is blocked with Smoke keyword
   it('Identify element with Id - Smoke', function(){
      // launch url
      browser.url('https://the-internet.herokuapp.com/redirector')
      //identify element with id then click
      $("#redirect").click()
      //obtain page title
      console.log('Page title after click: ' + browser.getTitle())
   });
   // it block with Smoke keyword
   it('Identify element with Tagname - Smoke', function(){    
      // launch url
      browser.url('https://tutorialspoint.tw/about/about_careers.htm')
      //identify element with tagname then obtain text
      console.log($("<h1>").getText() + " - is the text.")
   });
   //test case
   it('Identify element with Class Name', function(){        
      // launch url
      browser.url('https://tutorialspoint.tw/about/about_careers.htm')
      //identify element with Class Name then obtain text
      console.log($(".heading").getText() + " - is the text.")
   });
});

要僅觸發與“Smoke”相關的it塊,請使用以下命令執行配置檔案 - wdio.conf.js檔案:

npx wdio run wdio.conf.js --mochaOpts.grep Smoke

關於如何建立配置檔案的詳細資訊在標題為“wdio.conf.js檔案”和“配置檔案生成”的章節中詳細討論。

您的計算機上將出現以下螢幕:

Execute Tests Mocha Options

命令成功執行後,我們發現四個it塊中,只有兩個it塊(描述中帶有“Smoke”標籤)被執行。

廣告