定义和使用测试环境
概述
环境位于配置文件中的 "test_settings" 字典下。始终需要一个 default 环境,其他环境将继承该环境的设置。您可以根据需要覆盖每个环境的任何测试设置。
在本指南中,我们将创建一个名为 "chrome-local" 的新测试环境,我们将使用它来针对 Google Chrome 浏览器运行测试。
创建一个新的测试项目
首先,让我们创建一个新的空项目并在其中安装 Nightwatch
mkdir ./test-project && cd ./test-project
从 NPM 安装 nightwatch 和 chromedriver(chromedriver 是用于在 Google Chrome 浏览器中运行测试的 W3C WebDriver 实现)
npm i nightwatch chromedriver
创建一个名为 nightwatch.conf.js 的空文件
nano nightwatch.conf.js
并将以下内容粘贴到其中
nightwatch.conf.js
module.exports = {
src_folders: ['tests'],
test_settings: {
default: {
launch_url: 'https://home.cern',
webdriver: {
start_process: true,
server_path: ''
}
}
}
}使用 --env cli 参数引用测试环境。由于我们只定义了一个 default 环境,因此尝试引用 chrome-local 环境会导致错误
npx nightwatch --env chrome-local
~/workspace/test-project % npx nightwatch --env chrome-local
┌──────────────────────────────────────────────────────────────────┐
│ │
│ Error: Invalid testing environment specified: chrome-local. │
│ │
│ Available environments are: │
│ [ 'default' ] │
│ │
│ │
└──────────────────────────────────────────────────────────────────┘定义一个新的 "chrome-local" 环境
现在,再次打开 nightwatch.conf.js 文件,并在 default 对象下方添加 chrome-local 对象
nightwatch.conf.js
module.exports = {
src_folders: ['tests'],
test_settings: {
default: {
launch_url: 'https://home.cern',
webdriver: {
start_process: true,
server_path: ''
}
},
'chrome-local': {
desiredCapabilities: {
browserName: 'chrome'
}
}
}
}针对 "chrome-local" 环境运行示例测试
然后在 tests 文件夹中添加一个示例测试
mkdir tests && nano ./tests/sample-nightwatch-test.js
tests/sample-nightwatch-test.js
describe('sample nightwatch test', function() {
it('opens the browser and checks for input', function(browser) {
browser
.init()
.assert.titleEquals('Home | CERN')
.end();
});
})运行示例并传递 --env chrome-local 参数
npx nightwatch --env chrome-local
输出将类似于以下内容
[sample nightwatch test] Test Suite
──────────────────────────────────────────────────────────────────────
ℹ Connected to ChromeDriver on port 9515 (844ms).
Using: chrome (101.0.4951.64) on MAC OS X.
Running opens the browser and checks for input:
────────────────────────────────────────────────────────────────────────────────────────────────────────────────
ℹ Loaded url https://home.cern in 5531ms
✔ Testing if the page title equals 'Home | CERN' (6ms)
OK. 1 assertions passed. (5.604s)