Write End-to-End tests in Node.js quickly and effortlessly that run against a Selenium/WebDriver server.javascript
# 在当前项目中安装 npm i -D nightwatch # 或者全局安装 npm i -g nightwatch
Nightwatch有两种方式去调起浏览器跑测试java
我选择了第二种,这里就须要去安装的chrome的webDriver,有个npm包帮咱们作了这个事web
npm i -D chromedriver
安装的时候可能会遇到'网络问题',在根目录下新建一个.npmrc文件,指定一下下载路径chrome
chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
Nightwatch启动的时候默认会去加载nightwatch.json配置文件,nightwatch.js也行,这里贴上个人配置文件,并对一些经常使用的字段作一下说明,其他看文档就行shell
{ "src_folders": ["test/ui"], "output_folder": "reports", "custom_commands_path": "", "custom_assertions_path": "", "page_objects_path": "", "globals_path": "./webDriver.js", "selenium": { "start_process": false }, "test_settings": { "default": { "selenium_port": 9515, "selenium_host": "localhost", "default_path_prefix": "", "desiredCapabilities": { "browserName": "chrome", "chromeOptions": { "args": [ "--no-sandbox", "user-data-dir=/Users/shenshuaijia/Library/Application Support/Google/Chrome" ] }, "acceptSslCerts": true }, "globals": { "domain": "http://xxx.com" } } } }
globals_path: 全局模块路径,nightwatch启动时还会去加载这个路径下的模块,好比咱们刚刚下载了Chromedriver,咱们须要写个模块文件,简单包装一下暴露出来被nightwatch加载。 这是我根目录下的webDriver.js文件,这样的话,nightwatch就能经过这个文件调webdriver而后启动浏览器了npm
const chromedriver = require('chromedriver') module.exports = { before: function(done) { chromedriver.start() done() }, after: function(done) { chromedriver.stop() done() } }
nightwatch --env default
使用default那一套配置,也能够用nightwatch --env integration
来运行integration那套配置,但须要事先在test_settings中有配置这里我遇到了一个比较特殊的状况,我须要使用平时使用chrome留下的cookie,而不是彻底的沙盒模式,因此,我这里须要启动chromedriver的时候,指定加载chrome用户数据的文件夹"user-data-dir=/Users/xxx/Library/Application Support/Google/Chrome"
,这样全部的登陆信息都能在测试的时候被使用。json
browser.globals.domain
获取在test/ui
文件夹下新建一个测试文件page.test.js
浏览器
module.exports = { 'Demo test Google' : function (browser) { browser .url('http://www.google.com') .waitForElementVisible('body', 1000) .setValue('input[type=text]', 'nightwatch') .waitForElementVisible('button[name=btnG]', 1000) .click('button[name=btnG]') .pause(1000) .assert.containsText('#main', 'Night Watch') .end(); } }
nightwatch拥有比较优雅的测试写法。这里就是简单打开一个谷歌页面,往输入框输入nightwatch而后点击按钮。记住全部的测试完成后须要调end方法来退出浏览量。nightwatch也能够定义一些钩子函数cookie
module.exports = { before : function(browser) { console.log('Setting up...'); }, after : function(browser) { console.log('Closing down...'); }, beforeEach : function(browser) { }, afterEach : function() { }, 'step one' : function (browser) { browser // ... }, 'step two' : function (browser) { browser // ... .end(); } };
nightwatch
这里我遇到了一个奇怪的问题,多是因为我指定了用户目录的关系,我须要先彻底退出chrome,在跑测试,否则跑测试新打开的窗口不会按代码里写的测试去走网络
这里我只是简单介绍一下nightwatch,更加详细具体的使用仍是须要参考官方文档。有了ui自动化测试之后,咱们能够简单的作一些回归测试,好比,改了某些代码之后,把全部的页面都跑一遍,看看控制台有没有报错,比点点点方便多了