[AngularJs] 使用Protractor作前端測試-入門

   前陣子去Techday時聽這堂課時"DEV 204 使用 AngularJS 在 ASP.NET 專案上開發企業水準的應用,講師有提到使用Protractor來作前端的單元測試,但他沒介紹如何使用….=.=,為了一解心中疑惑,Survey相關教學後,將相關使用環境、方式整理如下:

什麼是Protractor

  它是AngularJs專門用來作前端測試的工具,透過nodejs上的selectium,執行chrome、fiirefox、IE等瀏覽器,來模擬使用者操作行為並驗證你撰寫好的AngularJs程式是否正確。

 

執行環境

  1. AngularJs:測試的網頁一定要內含AngularJs,否則會出現沒有Angular的錯誤 ,修正:可以使用browser.driver來撰寫
  2. Java Runtime:selectium的執行環境
    image
    http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html
  3. NodeJs:Protractor的執行環境

撰寫測試程式

index.html
此檔案會用來測試回應的title
image
index.spec.js
單元測試程式,如下為使用browser物件執行index.html並取回title作比對是否為預期值
image
ps:最外頭的describe為描述測試方法的內容
protractor.conf.js
單元測試程式的定義檔,1.baseUrl:指定測試的Url,2.specs指定要測試哪些檔案,如下圖指定spec目錄下所有副檔名為.spec.js的檔案
image

 

套件安裝

執行nodejs command prompt
1.protractor安裝
npm install -g protractor
2.webdriver更新 selectium
webdriver-manager update

ps:for chrome v54的driver 更新
webdriver-manager update --standalone true --versions.chrome 2.24

執行測試



1.執行web server
本例是透過nodejs來執行index.js(若你使用其他Web環境,可以忽略此項)
image

index.js
image

2.透過protractor指令執行測試
protractor protractor.conf.js

執行後,瀏覽器會被叫起來瀏覽index.html,此時protractor會取得回傳內容並與測試程式作驗證

image

測試完畢後,瀏覽器會關閉並輸出結果,如下:執行1個測試,成功1個、失敗0個

image

參考來源

https://egghead.io/lessons/angularjs-getting-started-with-protractor

https://github.com/angular/protractor

https://docs.angularjs.org/guide/e2e-testing


範例程式

https://github.com/kimx/protractorLab/

這個網誌中的熱門文章

IIS 設定只允許特定IP進入