# Nightwatch.js 網頁自動化測試
---
### What is Selenium ?
http://www.seleniumhq.org/
![](https://i.imgur.com/MDpd2hU.png)
---
### What is nightwatch ?
Write End-to-End tests in Node.js quickly and effortlessly that run against a Selenium/WebDriver server.
http://nightwatchjs.org/
![](http://nightwatchjs.org/img/operation.png)
---
### package.json
```
{
"name": "test selenium",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nightwatch"
},
"author": "",
"license": "ISC",
"dependencies": {
"chrome-driver-standalone": "^2.25.0",
"nightwatch": "^0.9.9"
"selenium-server-standalone-jar": "^3.0.1"
}
}
```
---
### How nightwatch start selenium ?
在執行 nightwatch 之前要先有一個設定檔案告訴 nightwatch 一些你連線的資訊
```javascript=
var selenium = require('selenium-server-standalone-jar');
var chromeDriver = require('chrome-driver-standalone');
var config = {
"src_folders": ["test"],
"selenium": {
"start_process": true,
"server_path": selenium.path,
"cli_args": {
"webdriver.chrome.driver": chromeDriver.path
}
},
"test_settings": {
"default": {
"globals": {
"waitForConditionTimeout": 30000
},
"desiredCapabilities": {
"browserName": "chrome",
}
}
}
}
module.exports = config;
```
---
### practice
[repository tag v1.0](https://github.com/chnbohwr/nightwatch_example/tree/v1.0)
功能
1. login github
2. create new repository
3. delete repository
---
### tip 1 coding style
好的測試項目應該盡量不要使用`pause` 並且要有驗證的機制
```
.click('input.btn')
//.pause(3000)
.waitForElementVisible('img.avatar')
.click('.header-nav-link.tooltipped.tooltipped-s.js-menu-target')
```
[repository](https://github.com/chnbohwr/nightwatch_example/tree/v1.1)
---
### tip2 extract module
把重複使用率高的功能抽出來變成模組
```
browser
.resizeWindow(1920, 1080)
.login(username, password)
.createRepository(repositoryName)
.deleteRepository(username, repositoryName)
.end()
```
[repository](https://github.com/chnbohwr/nightwatch_example/tree/v1.2)
---
### tip3 page object
使用 page object 減少維護的複雜
[url](http://nightwatchjs.org/guide#page-objects)
[repository](https://github.com/chnbohwr/nightwatch_example/tree/v1.3)
---
### tip4 遇到的雷
phantomjs 可以用,但是不建議
firefox 的 不一定比 chrome 還穩定
docker 的 container 裡面中文顯示有問題,要用 class/id 判斷
---
### tip5 不想開瀏覽器的方法
phantomjs 不好用
[DOCKER 比較穩定](https://hub.docker.com/r/selenium/standalone-chrome/)
![](https://i.imgur.com/vtI05rY.png)
---
### FAQ
{"metaMigratedAt":"2023-06-14T12:10:10.362Z","metaMigratedFrom":"Content","title":"Nightwatch.js 網頁自動化測試","breaks":true,"contributors":"[]"}