天天看點

使用Nightwatch.js做基于浏覽器的web應用自動測試

1        安裝

1.1   安裝node.js

在http://nodejs.org/ 上下載下傳适合本機系統的安裝包運作安裝,注意安裝選項中選擇npm tool以用于後續依賴包的安裝。

使用Nightwatch.js做基于浏覽器的web應用自動測試

1.2   通過npm工具安裝nightwatch

指令行運作“npm install nightwatch”,如下的提示表明安裝成功。

使用Nightwatch.js做基于浏覽器的web應用自動測試

1.3   npm相關目錄結構

所有npm安裝的子產品都會基于目前cmd視窗的目錄,也就是說如果cmd的工作目錄是在c:\根目錄,則會在該目錄下建立node_modules檔案夾,并将安裝的子產品都放到該目錄下,如果通過windows附件程式或者win+r啟動的,則工作目錄在“%userprofile%\”下。

npm安裝所下載下傳的臨時檔案儲存在“%appdata%\npm-cache”下。

1.4   下載下傳selenium webdriver server

http://selenium-release.storage.googleapis.com/index.html上下載下傳最新版本的jar包,并将其放到nightwatch的bin目錄下。

2        執行個體使用

2.1   nightwatch.js中增加引用

在”\node_modules\nightwatch\examples\tests\nightwatch.js”中增加引用“require('../../bin/runner.js');”

2.2  運作selenium webdriver server(進入jar所在目錄, 我的目錄是d:\nodejs\node_modules\nightwatch\bin,運作指令“java -jar 2.53.1-server.jar”

2.3   運作nightwatch.js

指令行下,cd到nightwatch所在的目錄(我的目錄是d:\nodejs\node_modules\nightwatch),然後運作“node ./examples/tests/nightwatch.js”

使用Nightwatch.js做基于浏覽器的web應用自動測試

 我用的chrome浏覽器,我将chromedriver.exe放置在目錄d:\nodejs\node_modules\nightwatch\bin下, nightwatch.json配置檔案如下:

  

2.3   異常處理

如果沒意外,執行上述js的時候會抛類似下面的異常,不要慌張,根據異常提示,安裝所需要的module即可,安裝方法“npm install xxx”。

使用Nightwatch.js做基于浏覽器的web應用自動測試

3        基本原理

使用Nightwatch.js做基于浏覽器的web應用自動測試

4        測試套件

nightwatch.js makes it possible to organizedyour test scripts into groups and run them as needed. to group tests togetherjust place them in the same sub-folder. the folder name is the name of thegroup.例如下面的目錄結構。

使用Nightwatch.js做基于浏覽器的web應用自動測試

5        自己的腳本

在nightwatch根目錄下建一個名為test.js的檔案:

require('./bin/runner.js');

var nightwatch = require('./index.js');

module.exports = {

 "step one" : function (browser) {

   browser

     .url("http://www.google.com.hk")

     .waitforelementvisible('body', 1000)

     .setvalue('input[type=text]', 'nightwatch')

     .waitforelementvisible('button[name=btng]', 1000)

 },

 "step two" : function (browser) {

     .click('button[name=btng]')

     .pause(1000)

     .assert.containstext('#main', 'the night watch')

     .end();

  }

};

然後”node ./test.js”運作:

使用Nightwatch.js做基于浏覽器的web應用自動測試

更多的使用參見其api文檔:http://nightwatchjs.org/api

6        産品特征

Ø  simple but powerful syntax which enables you to write tests veryquickly, using only javascript and css selectors. no need to initialize otherobjects and classes, you only need to write the test specs.

Ø  built-in command-line test runner which enables you to run the testseither altogether, by group or single.

Ø  manages the selenium server automatically; can be disabled ifselenium runs on another machine.

Ø  continous integration support: junit xml reporting is built-in soyou can integrate your tests in your build process with systems suchs as hudsonor teamcity.

Ø  use css selectors or xpath to locate and verify elements on the pageor execute commands.

Ø  easy to extend if you need to implement your own commands specificto your application.

繼續閱讀