Nightwatch.js 是一個用來測試web應用和網站的自動化測試框架,它是由NodeJs
編寫的,使用了W3C WebDriver API
(之前是Selenium WebDriver
)
所以我們首先是要安裝NodeJs:
1.首先,從Node.js官網下載對應平台的安裝程序,網速慢的童鞋請移步國內鏡像,在Windows上安裝時務必選擇全部組件,包括勾選Add to Path
。
2.安裝完成后輸入 npm -v(npm是Node.js的包管理工具(package manager)
Nightwatch 安裝
1.完成后我們創建一個文件夾名為(nightwatch-test),名稱根據個人喜好
2.初始化項目: npm init -y
3.安裝依賴:npm install nightwatch
4.安裝seleniumserver服務:npm install selenium-server
5.安裝谷歌驅動:npm install chromedriver ps:這邊要根據你的瀏覽器版,有可能會版本不兼容的情況
從Chrome75版本開始,就默認使用了W3C的webdriver協議,但nightwatch用的是JSONWP,和W3C不兼容,所以如果想要正常使用,必須關閉W3C的協議。也就是說,可以在測試文件里加上這么一段:
module.exports = { desiredCapabilities: { browserName: "chrome", chromeOptions: { w3c: false } } }
Nightwatch配置
在項目的根目錄下新建一個nightwatch.conf.js
文件,然后將以下的代碼拷貝進去。
module.exports = { src_folders: ['examples'],//這邊的src_folders的值為運行的測試目錄 output_folder: 'output', custom_assertions_path: [], page_objects_path: '', globals_path: '', selenium: { start_process: true, server_path: require('selenium-server').path, host: '127.0.0.1', port: 5555, cli_args: { 'webdriver.chrome.driver': require('chromedriver').path } }, test_settings: { default: { selenium_port: 5555, selenium_host: 'localhost', silent: true, globals: { devServerURL: 'http://localhost:' + (process.env.PORT || 1111) } }, chrome: { desiredCapabilities: { browserName: 'chrome', javascriptEnabled: true, acceptSslCerts: true } }, firefox: { desiredCapabilities: { browserName: 'firefox', javascriptEnabled: true, acceptSslCerts: true } } } }
Nightwatch 腳本編寫
1.在項目的根目錄下新建一個examples(必須跟你剛才在src_folder下設置的名稱一直)的文件夾,用於存放我們的測試腳本。接着新建一個js文件作為測試文件
2.創建腳本js文件
module.exports = {
desiredCapabilities: {
browserName: "chrome",
chromeOptions: {
w3c: false
}
},
'search nightwatch on baidu': function (browser) {
browser
.url('https://www.baidu.com/')
.waitForElementVisible('body', 1000)
.setValue('#kw', 'nightwatch')
.click('#su')
.pause(3000)
.waitForElementVisible('#content_left', 3000)
.end();
}
};
3.創建第二個js腳本
module.exports = { 'search nightwatch on baidu': function (browser) { browser .url('http://192.xxx.x.xx:6013/') .waitForElementVisible('body', 1000) .useXpath() .setValue('//*[@id="app"]/div/div/form/div[1]/div/div/input', 'admin') .setValue('//*[@id="app"]/div/div/form/div[2]/div/div/input', '123456') .click('//*[@id="app"]/div/div/form/div[3]/div/button') .pause(3000) .end(); } };
運行測試用例
1.接着我們在package.json的scripts
中"e2e": "nightwatch --env chrome"加入運行腳本:
{ "name": "nightwatch-test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "e2e": "nightwatch --env chrome", //路徑 "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "nightwatch": "^1.0.19", "selenium-server": "^3.141.59" } }
接着在項目根目錄下運行:
npm run e2e
強烈推薦學習地址: