概觀

環境位於設定檔的 "test_settings" 字典下。始終需要一個 default 環境,其他環境會從該環境繼承設定。您可以根據需要覆寫每個環境的任何測試設定。

在本指南中,我們將建立一個新的測試環境,稱為 "chrome-local",我們將使用它來針對 Google Chrome 瀏覽器執行測試。

建立新的測試專案

首先,讓我們建立一個新的空專案,並在其中安裝 Nightwatch

mkdir ./test-project && cd ./test-project

從 NPM 安裝 nightwatchchromedriverchromedriver 是 W3C WebDriver 實作,用於在 Google Chrome 瀏覽器中執行測試)

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)