iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 13
2
DevOps

Nightwatch101:使用 Nightwatch 實現 End-to-End Testing系列 第 13

Nightwatch101 #13:Test Hooks

Nightwatch.js

Nightwatch 提供 before/after 與 beforeEach/afterEach 鉤子。

♡(´∀`)人(´∀`)♡

本系列文章皆使用這個專案,可以拉下來玩玩;有什麼問題都可以提出 issue


說明

  • before():test suite 開始前,也就是在該檔案所有 test case 開始前會執行的程式碼區塊。
  • after():test suite 結束後,也就是在該檔案所有 test case 結束後會執行的程式碼區塊。
  • beforeEach():在該檔案每個 test case 開始前執行的程式碼區塊。
  • afterEach():在該檔案每個 test case 結束後執行的程式碼區塊。

Test Hooks 多用於為 test suite 或 test case 的環境設定等前置作業、登入或登出等重覆性的工作。

範例

執行以下指令。

nightwatch test/e2e/class/testMainCategoryHooks.js

範例程式碼如下。這裡會執行兩個 test case,分別來觀察鉤子的執行狀況。

module.exports = {
  before : function(browser) {
    console.log('Setting up...');
  },
  after : function(browser) {
    console.log('Closing down...');
  },
  beforeEach : function(browser) {
    console.log('Before each test case...');
  },
  afterEach : function(browser, done) {
    console.log('After each test case...');
    done();
  },
  'Assert Ruten MainCategory Title 0008': browser => {
    browser.url('http://class.ruten.com.tw/category/main?0008');
    browser.waitForElementVisible('body');
    browser.expect.element('.rt-flagship .rt-ad-heading').text.to.equal('露天旗艦店');
    browser.end();
  },
  'Assert Ruten MainCategory Title 0011': browser => {
    browser.url('http://class.ruten.com.tw/category/main?0011');
    browser.waitForElementVisible('body');
    browser.expect.element('.rt-flagship .rt-ad-heading').text.to.equal('露天旗艦店');
    browser.end();
  }
}

看完整範例

因此...

  • 「Setting up...」共執行了一次,並且是在 test suite 開始的時候執行。
  • 「Before each test case...」共執行了兩次,並且是在每個 test case 開始的時候執行。
  • 「After each test case...」共執行了兩次,並且是在每個 test case 結束的時候執行。
  • 「Closing down...」共執行了一次,並且是在 test suite 結束的時候執行。

Test Hooks

關於 Test Globals 的應用

Test Globals 是存放一些名-值對(Name-Value Pairs)的地方,用於代入測試程式中使用(點此複習 Test Globals)。

在 Test Globals 中定義一個 counter 代入 test case,初始值是 0,做加 1 的動作,顯示結果為 1。

nightwatch.conf.js 的設定。

"test_settings": {
  "local": {
    // 省略以上設定
    "globals": {
      "counter": 0
    }
  }
}

範例程式碼。

module.exports = {
  before : function(browser) {
    console.log('Setting up...');
    console.log('counter: ' + browser.globals.counter);
    browser.globals.counter++;
    console.log('counter: ' + browser.globals.counter);
  },
  'Demo Test': browser => {
    browser
      .url('https://cythilya.github.io/')
      .waitForElementVisible('body')
      .end()
    }
}

執行結果。

關於 Test Globals 的應用

下一篇來看 Asynchronous Test Hooks


網誌版


上一篇
Nightwatch101 #12:BDD Verify
下一篇
Nightwatch101 #14:Asynchronous Test Hooks
系列文
Nightwatch101:使用 Nightwatch 實現 End-to-End Testing30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言