nel*_*nic 1 javascript testing selenium node.js nightwatch.js
情况:我们正在使用Nightwatch在几个浏览器中运行测试
(通过Saucelabs;一切都在Saucelabs上正常运行).
期望:我们想知道当前运行的测试浏览器,以便我们可以保存包括浏览器名称在内的屏幕截图.
是否可以确定哪个浏览器正在运行测试?
它很简单,在运行Nightwatch测试时,传入browser(或client)参数,例如:
module.exports = {
'Demo test GitHub': function (browser) {
console.log(browser.options); // this will output the browser details
browser
.url('http://www.github.com/dwyl') // visit the url
.waitForElementVisible('body'); // wait for the body to be rendered
.assert.containsText('body', 'do what you love') // assert contains
.saveScreenshot('dwyl_github.png')
.end();
}
};
Run Code Online (Sandbox Code Playgroud)
该browser对象包含options有以下表单对象:
{ screenshots: true,
screenshotsPath: './node_modules/nightwatch/screenshots/1.0.20/',
skip_testcases_on_fail: true,
log_screenshot_data: true,
username: 'thisguy',
accessKey: 'notimportant',
desiredCapabilities:
{ browserName: 'internet explorer',
javascriptEnabled: true,
acceptSslCerts: true,
platform: 'Windows 10',
version: '11.0',
name: 'Github' } }
Run Code Online (Sandbox Code Playgroud)
所以我们编写了一个小帮助函数来将浏览器的名称格式化为我们可以包含在屏幕截图文件名中的字符串:
function userAgent(browser) { // see: https://git.io/vobdn
var a = browser.options.desiredCapabilities;
return (a.platform + '~' + a.browserName + '~' + a.version).replace(/ /g, '');
}
Run Code Online (Sandbox Code Playgroud)
然后用作:
module.exports = {
'Demo test GitHub': function (browser) {
console.log(browser.options); // this will output the browser details
browser
.url('http://www.github.com/dwyl') // visit the url
.waitForElementVisible('body'); // wait for the body to be rendered
.assert.containsText('body', 'do what you love') // assert contains
.saveScreenshot(userAgent(browser) + '_dwyl_github.png')
.end();
}
};
Run Code Online (Sandbox Code Playgroud)
示例文件名: Windows10~internetexplorer~11.0~dwyl_github.png
使用~("tilde")作为单词分隔符的原因是我们稍后可以split在屏幕截图查看器中使用此字符.有关更多详细信息,请参阅:https://github.com/dwyl/learn-nightwatch.