Nightwatch——自動化測試(端對端e2e)

背景:javascript

前端頁面模擬仿真操做,目的是避免每次更新相關內容重複以前的測試操做,減小沒必要要的時間投入,以及校驗功能的可用性。可是目前元素定位是個問題(每次頁面有修改都要重設某些元素定位)css

使用Nightwatch進行E2E測試

E2E測試

不一樣於行爲驅動測試(BDD)和單元測試獨立運行並使用模擬/存根,端到端測試將試着儘量從用戶的視角,對真實系統的訪問行爲進行仿真。對Web應用來講,這意味着須要打開瀏覽器、加載頁面、運行JavaScript,以及進行與DOM交互等操做。
然而,項目在快速迭代中不可避免的要進行一遍又一遍測試,費時又費力,並且極有可能因人工失誤忽略某些環節。再者,怎麼能容忍一次搞定的事非要屢次重複呢?不能忍啊。萬能的程序員們總會有辦法解決如此循環往復的重複性工做,因而,三年前的某個月黑風高的夜晚,Nightwatch誕生了(雖然這貨最新的release版本是五天以前的v0.9.14)。前端

Nightwatch 簡介

Nightwatch.js是一個基於Node.js的端到端(e2e)測試方案,使用W3C WebDriver API,將Web應用測試自動化。它提供了簡單的語法,支持使用JavaScript和CSS選擇器,來編寫運行在Selenium服務器上的端到端測試。vue

Selenium至關於一個自動化的瀏覽器,是用於Web應用程序測試的工具。Selenium測試直接運行在瀏覽器中,就像真正的用戶在操做同樣。支持的瀏覽器包括IE、Mozilla Firefox、Mozilla Suite等(其實Selenium就是一個jar包)java

目前,Selenium是JavaScript的世界裏驗收測試方面最流行的工具之一,相似的還有PhantomJS。兩者都有其獨到的方法:Selenium使用其WebDriver API,而PhantomJS使用無界面的WebKit瀏覽器。它們都是很是成熟的工具,都具備強大的社區支持。它們與Nightwatch之間最大的不一樣,主要是在於語法的簡易度以及對持續集成的支持。與Nightwatch相比,Selenium和PhantomJS都擁有更加冗長的語法,這會讓編碼變得更龐大,並且不支持從命令行中進行開箱即用的持續集成(JUnit XML或其餘標準輸出)。node

p.s. Selenium和PhantomJS都是能夠單獨做爲一種測試方案,Nightwatch是基於Selenium的一種更簡潔的測試方案。程序員

p.s. WebDriver目前已是W3C的一個規範,旨在規範瀏覽器的自動化行爲web

p.s. 我是咋知道有這麼個東西的?實際上是Vue全家桶裏給帶的。chrome

Nightwatch工做時時依託於一套基於HTTP的REST API,只不過Server端不是傳統意義上的後端,而是WebDriver的服務器(Selenium),這套REST API是基於W3C WebDriver API的。
就像這樣:npm

work flow

大部分的狀況下,Nightwatch執行一條命令或者斷言迴響WebDriver發送兩個請求,第一個請求用來獲取到CSS或XPath選擇器選中的那個element節點,第二個請求用來發送這條命令或者斷言。

Nightwatch的主要特色

  • 語法簡潔乾淨
  • 支持CSS選擇器和XPath選擇器,只要編寫的測試用例符合規範,就無須再初始化其餘對象和類。
  • 內置命令行測試運行器,能夠按組或單個運行測試。
  • 能夠持續集成
  • 易擴展

在項目中使用Nightwatch

先貼一個例子【這是用來測kz-fe中node-arch的首頁的一個用例片斷】

'default tests': function (browser) {
      const devServer = browser.globals.devServerURL;

      browser
        .url(devServer)
        .waitForElementVisible('body', 2000)
        .assert.attributeContains('body', 'class', 'directory') 
        .assert.elementPresent('input') 
        .assert.attributeEquals('#search', 'placeholder', 'Search') 
        .assert.cssProperty('#search', 'position', 'fixed')
        .assert.elementPresent('#wrapper')
        .end()
  }

在項目中使用Nightwatch須要安裝三個npm包:

  • chromedrive
  • nightwatch
  • selenium-server

而後須要一個配置文件:

{
  "src_folders": ["test/e2e/specs"], // 放測試用例
  "output_folder": "test/e2e/reports", // 放測試報告

  "selenium" : {
    "start_process" : true,
    "server_path": "node_modules/selenium-server/lib/runner/selenium-server-standalone-3.3.1.jar",
    "host": "127.0.0.1",
    "log_path" : "",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : ""
    }
  },

  "test_settings" : {
    "default" : {
        "launch_url" : "http://localhost",
        "selenium_port"  : 4444,
        "selenium_host"  : "localhost",
        "silent": true,
        "globals": {
            "devServerURL": "http://localhost:8080"
        }
    },

    "chrome" : {
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true
      }
    },

    "edge" : {
        xxxx略
      }
    }
  }
}

而後就能夠愉快地寫測試用例了。

Nightwatch API

Nightwatch API分爲四個部分,分別是Expect、Assert、Commands、WebDriver Protocol

Expect

Expect是0.7版本的時候引入的一種BDD(行爲驅動測試)風格的接口,也是爲了執行斷言,使用鏈式的語法,和直接的斷言相比,expect讀起來更加語義化,就像寫句子(可是單詞之間用的.鏈接的)

this.demoTest = function (browser) {
  browser.expect.element('#main').to.be.present;
  browser.expect.element('#main').to.be.visible;
  browser.expect.element('#main').to.have.css('display').which.does.not.equal('block');
  browser.expect.element('#q').to.be.an('input');
  browser.expect.element('body').to.not.have.attribute('data-attr');
};

Expect提供的語言連詞不直接進行斷言(真正的斷言是末尾的那個詞),能夠隨意組合,順序不影響結果。

to 、be 、been 、is 、that、which、and、has、have、with、at、does

Assert

Assert這部分包含兩套有一樣方法的方法庫:assert和verify,其中,如果當前執行的斷言沒有成功,assert會中止執行剩餘的斷言並當即結束,verify會打印錯誤日誌而後繼續淡定的執行接下來的斷言。

 browser
        .url(devServer)
        .waitForElementVisible('body', 2000)
        .assert.attributeContains('body', 'class', 'directory') // 屬性值
        .assert.elementPresent('input') // 有當前元素
        .assert.attributeEquals('#search', 'placeholder', 'Search') // 屬性值
        .assert.cssProperty('#search', 'position', 'fixed') // CSS屬性值
        .assert.elementPresent('#wrapper')
        .end()

Commands

Commands用來在頁面上執行一些命令好比點擊、關掉當前窗口、清除cookie、獲取到某元素的值等。

this.demoTest = function (browser) {

  browser.click("#main ul li a.first", function(response) {
    this.assert.ok(browser === this, "Check if the context is right.");
    this.assert.ok(typeof response == "object", "We got a response object.");
  });
  browser.clearValue('input[type=text]');
  browser.pause(1000);
  browser.saveScreenshot('/path/to/fileName.png');
  browser.closeWindow();

};

測試分類:

一.單元測試:站在程序員的角度測試;

一、減小開發人員的重複測試時間 二、面向程序的功能模塊的測試

二.端對端測試:站在測試人員的角度測試

一、減小測試人員的重複測試時間 二、面向系統的功能模塊的測試 三、本質是模擬用戶使用系統

測試插件:

Nightwatchjs:https://nightwatchjs.org/

主要包括:一、元素定位 二、斷言 三、POM

準備工做:

1.安裝(vue3.0已經內置nigjtwatch.js):來自NPM

npm install nightwatch

使用WebDriver兼容服務器來控制瀏覽器

desiredCapabilities : {
  browserName : ' chrome ',
  chromeOptions : {
    w3c : false
  }
}

2.配置文件:package.json

  "scripts": {
    "e2e": "node test/e2e/runner.js --tag testDemo 
    "test": "npm run unit && npm run e2e",
    "lint": "eslint --fix --ext .js,.vue src test/unit test/e2e/specs",
  }

3.元素定位:在test/e2e/POM文件夾建立js文件

const config = require('../config.js')
module.exports = {
  url: config.host + '/admin/activityTypeManage?__test=luoganluo',
  elements: { //對象或數組形式
    // 'newAppButton': {selector: '#KP_appManage > div > div.el-card__body > div > div > div.el-row > div:nth-child(2) > button:nth-child(1)'}, //方式1:selector
    'newBusinessButton': { locateStrategy: 'xpath', selector: '//*[@id="activityManage"]/div[1]/div/button/span' }, // 方式2:xpath
    ...
  }
}

快速定位:

1.啓動本地服務npm run dev,打開瀏覽器按F12調試——按ctrl+shift+C快速定位元素——單擊右鍵選擇Copy獲取選擇器內容(以上2種方式);

2.路由定位:打開頁面是,直接設置須要進入的頁面路由便可(參數設置)

 

4.斷言:判斷操做出現正確的結果(在test/e2e/specs文件夾建立js文件)

module.exports = {
  '@tags': ['testDemo '],
  before: function (browser) {
    // util(browser).login()
  },
  '測試demo': function (browser) {
    browser.maximizeWindow() //屏幕最大化
    var loginPage = browser.page.loginPage()// 打開應用列表頁面
    loginPage.navigate()/// /打開應用列表頁面
      .waitForElementVisible('@loginButton', 5000)//等待頁面出現
      .click('@loginButton')// 點擊新建
      .click('@clickToShowBusinessSelect') //點擊下拉選項
      .pause(500) //等待選項出現
      ...
  },
  after: function (browser) {
  }
}

實例:

module.exports = {
  '@tags': ['appList'],
  before: function (browser) {
    // util(browser).login()
  },
  '測試新建業務': function (browser) {
    browser.maximizeWindow()
    var appList = browser.page.appList()// 0.1.打開應用列表頁面
    // appList.assert.containsText("@newAppButton",'新建應用') //分步寫:
    appList.navigate()// 1.打開應用列表頁面
      .waitForElementVisible('@appListPage', 5000)
      .assert.containsText('@appListPage', '應用列表') // 列表頁面
      .click('@newAppButton') // 1.點擊新建**********************
      .waitForElementVisible('@newListPage', 5000)
      .assert.containsText('@newListPage', '基本信息') // 新建頁面
      .setValue('@appListName', '新建應用名') //  + Number(new Date())
      .click('@appListTypeClick')// 點擊:接入方式
      .waitForElementVisible('@appListTypeSlected', 5000)
      .click('@appListTypeSlected')// 點擊選項
      .click('@appListSubmit')// 提交新建:延時
      .pause(1000)
      .click('@appManageTab') // 返回列表頁
      .pause(2000)
      // .waitForElementVisible('@editAppButton')
      // .assert.containsText('@editAppButton', '查看編輯') // 編輯按鈕
      // .click('@editAppButton') // 2.點擊編輯**********************
      // .waitForElementVisible('@editListPage', 5000)
      // .assert.containsText('@editListPage', '基本信息') // 編輯頁面
      // .click('@editListMenu') // 定位
      // .waitForElementVisible('@editAppListIcon', 5000)
      // .click('@editAppListIcon')
      // .waitForElementVisible('@editAppListName', 5000)
      // .setValue('@editAppListName', '編輯應用名') //  新的名稱
      // .click('@editAppListSubmit')// 提交編輯:延時
      // .pause(5000)
      // .click('@appManageTab') // 返回列表頁
      // .waitForElementVisible('@appListPage')
      // .assert.containsText('@appListPage', '應用列表') // 刷新列表:延時
      .click('@moreAppButtonClick') // 3.點擊更多(刪除)**********************
      .waitForElementVisible('@delAppButtonSlected', 5000)
      .assert.containsText('@delAppButtonSlected', '刪除應用')
      .click('@delAppButtonSlected')
      .waitForElementVisible('@delAppButtonSubmit', 5000)
      .assert.containsText('@delAppButtonSubmit', '肯定')
      .click('@delAppButtonSubmit') // 提交1:延遲
      .pause(1000)
      .click('@delAppButtonSubmit') // 提交2:確認刪除
      .pause(3000)
  },
  after: function (browser) {
  }
}

5.啓動測試:

npm run e2e

附:經常使用斷言語句總結

.waitForElementNotPresent('@editLoadingMask') // 等待加載消失

.waitForElementNotVisible('@dialogWrap') // 等待彈框消失

.assert.hidden('@newComDialog') //檢查對話框dialog隱藏

.assert.cssClassPresent('@switchChange', 'is-checked') //校驗是否存在class屬性

.assert.cssClassNotPresent('@switchChange', 'is-checked') //沒有出現這個class屬性

.assert.containsText('@newListPage', 'xxx') // 校驗元素內容是否等於xxx

.expect.element('@firstLogProtocolTitle').text.to.not.contain('xxx') // 內容不等於xxx

.assert.value('@newLogProtocolInput', 'xxx') //判斷當前內容是否爲xxx

.assert.urlContains('whiteListMock') // 檢查當前url包含whiteListMock
相關文章
相關標籤/搜索