nightwatch入门教程
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
强烈推荐学习地址:

浙公网安备 33010602011771号