[02] 前端測試工具集錦

https://qaseven.github.io/2016/05/24/front-end-tools/

1.e2e test

e2e或者端到端(end-to-end)或者UI測試是一種測試方法,它用來測試一個應用從頭至尾的流程是否和設計時候所想的同樣。簡而言之,它從一個用戶的角度出發,認爲整個系統都是一個黑箱,只有UI會暴露給用戶。javascript

具體連接看:http://sentsin.com/web/658.htmlcss

front-end-tools

總結最近了解的前端測試的相關內容,發現前端這裏真的是太龐大了,並且各類測試工具層出不窮,須要總結東西太多了,若有遺漏請你們見諒。html

TDD vs BDD:

TDD與BDD概念再也不描述了,直奔主題。前端

前端BDD測試框架

jasmine
Installationjava

install -g jasminenode

1
2
3
4
5
```
Initializing
To initialize a project for Jasmine
 
```jasmine init

To seed your project with some examplesjquery

examplesios

1
2
3
4
```
Usage
To run your test suite
``` jasmine
1
2
3
4
5
describe( "A suite", function() {
it( "contains spec with an expectation", function() {
expect( true).toBe(true);
});
});

mocha(推薦,簡潔明瞭)git

Installationangularjs

Install with npm:

1
$ npm install -g mocha

 

Getting Started

1
2
3
$ npm install -g mocha
$ mkdir test
$ $EDITOR test/test.js

 

In your editor:

1
2
3
4
5
6
7
8
9
var assert = require('chai').assert;
describe( 'Array', function() {
describe( '#indexOf()', function () {
it( 'should return -1 when the value is not present', function () {
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
});
});
});

 

you need to install chai.
Back in the terminal:

1
2
3
4
5
6
7
8
9
10
$ mocha
 
.
 
1 test complete (1ms)
```
### 前端TDD測試框架
 
Qunit
Installation

 

$ npm i qunit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
API
http: //api.qunitjs.com
 
Qunit是一款強大的用於幫助調試代碼的,JavaScript單元測試框架。QUnit由jQuery團隊成員編寫,是jQuery的官方測試套件,不只如此,QUnit還能夠測試任何常規JavaScript代碼,甚至能夠經過一些像Rhino或者V8這樣的JavaScript引擎,測試服務端JavaScript代碼。
 
能夠想象其跟jquery UI及jquery animation等庫結局同樣,逃脫不了各類被後來的庫全方位的比較和「超越」.
 
 
## Unit Testing
 
 
Mocha && Jasmine
 
Mocha 跟 Jasmine 是目前最火的兩個單元測試框架,基本上目前前端單元測試就在這兩個庫之間選了,下面是這兩個庫的區別,你們能夠根據本身的需求進行選擇:
 
mocha:
 
優勢:
終端顯示友好
靈活,擴展性好
缺點:
自身集成度不高(沒有斷言,spy,異步等),並且常常要配合Chai,Sinon等庫使用
配置相對麻煩一點點
 
Jasmine:
 
優勢:
集成度高,自帶BBD,spy,方便的異步支持( 2.0)
配置方便
缺點:
相對不太靈活
因爲各類功能內建,斷言方式或者異步等風格相對比較固定
沒有自帶mockserver, 若是須要這功能的得另外配置
 
jest
Jest 是Facebook的一個專門進行Javascript單元測試的工具.它是在Jasmine測試框架上演變開發而來,使用了咱們熟知的expect(value).toBe(other) 這種斷言格式。
 
First install Jest with npm by running:
npm install --save-dev jest-cli
1
2
 
Great! Now let's get started by writing a test for a hypothetical sum.js file:
function sum(a, b) {
  return a + b;
}
module.exports = sum;
1
Create a directory __tests__/ with a file sum-test.js:
jest.unmock('../sum'); // unmock to use the actual implementation of sum
describe('sum', () => {
  it('adds 1 + 2 to equal 3', () => {
    const sum = require('../sum');
    expect(sum(1, 2)).toBe(3);
  });
});
1
Add the following to your package.json:
"scripts": {
  "test": "jest"
}
1
Run npm test:
[PASS] __tests__/sum-test.js (0.010s)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
## 代碼覆蓋率工具
 
jscover
jscover是一個用來顯示JavaScript項目代碼覆蓋率的工具,它是繼承於JSCoverage的,用C++/SpiderMonkey 取代了Java/Rhino
 
可是已經淪落到淘汰的邊緣
 
Istanbul(推薦目前最強大前端代碼覆蓋率工具)
 
Istanbul 是 JavaScript 程序的代碼覆蓋率工具,
能產生 Statements/Lines/Functions/Branches 等指標報表,並以各類格式導出。
 
http: //qaseven.github.io/2016/01/25/gulp_for_qa/ 這篇文章裏已經詳細介紹了。
 
blanketjs
 
blanketjs是一個易於安裝,易於配置和易於使用的JavaScript代碼覆蓋庫 對於nodejs和瀏覽器都支持的不錯。
 
NodeJS (Powered by Mocha)
 
Install from npm.
npm install blanket
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Make sure you require Blanket before you require or run any of the code you want covered
 
require("blanket")({ /* optional options */ }),
require("src/myscripttotest");
 
Run your tests using mocha and take advantage of the json-cov and html-cov reporters to output the coverage results.
 
## e2e test
ui
 
webdriverio
 
這個庫是nodejs的一個webdriver模塊(瀏覽器自動化)。你能夠用它寫超級簡單 Selenium測試在你最喜歡的BDD / TDD測試框架中,而且能夠在本地運行或在雲端中, Sauce Lab,BrowserStack或TestingBot。
 
 
webdriverio 支持 Cucumber, Jasmine and Mocha+Chai 這些測試框架
 
nightwatch
 
Nightwatch.js 是一個易於使用的,基於 Node.js 平臺的瀏覽器自動化測試解決方案。它使用強大的 Selenium WebDriver API 來在 DOM 元素上執行命令和斷言。 語法簡單但很強大,使您能夠快速編寫測試。
只需使用 Javascript 和 CSS 選擇器,不須要初始化其餘對象和類,您只須要編寫測試規範。內置命令行測試運行器,使您可以運行總體測試,分組測試或者單個測試。
this.demoTestGoogle = function (browser) {
browser
.url(「http://www.google.com」)
.waitForElementVisible('body', 1000)
.setValue('input[type=text]', 'nightwatch')
.waitForElementVisible('button[name=btnG]', 1000)
.click('button[name=btnG]')
.pause(1000)
.assert.containsText('#main', 'The Night Watch')
.end();
};
1
2
3
4
5
6
 
當涉及異步調用時,基於鏈式的隊列是個糟糕的模式
 
CodeceptJS
 
CodeceptJS是一個基於WebDriver全新的端到端測試框架。它們從用戶角度簡單描述用戶操做步驟來編寫測試腳本
Feature('CodeceptJS Demonstration');

Scenario('test some forms', (I) => {
  I.amOnPage('http://simple-form-bootstrap.plataformatec.com.br/documentation');
  I.fillField('Email', 'hello@world.com');
  I.fillField('Password', '123456');
  I.checkOption('Active');
  I.checkOption('Male');  
  I.click('Create User');
  I.see('User is valid');
  I.dontSeeInCurrentUrl('/documentation');
});
1
2
3
4
5
 
protractor(angluarjs親兒子,由angluarjs核心人物開發的e2e測試工具)
protractor 是 AngularJS 團隊構建的一個端對端的測試運行工具,模擬用戶交互,幫助你驗證你的Angular應用的運行情況。
 
Protractor使用Jasmine測試框架來定義測試,固然你也能夠選擇其餘測試框架來定義測試,如mocha。Protractor爲不一樣的頁面交互提供一套健壯的API。
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('angularjs 首頁', function() {
  it('應該歡迎一個具名的用戶', function() {
    //要求瀏覽器訪問網址http://www.angularjs.org
    browser.get('http://www.angularjs.org');

    //找到ng-model名爲'youname'的HTML元素,要求瀏覽器鍵入名字
    element(by.model('yourName')).sendKeys('tanshuai');

    var greeting = element(by.binding('yourName'));

     //取得結果並做斷言測試
    expect(greeting.getText()).to.eventually.equal('Hello tanshuai!');
  });
});
1
2
3
4
5
6
7
8
9
10
11
 
## headless
 
PhantomJS
 
PhantomJS 是一個基於 WebKit 的服務器端 JavaScript API。它全面支持web而不需瀏覽器支持,其快速,原生支持各類Web標準: DOM 處理, CSS 選擇器, JSON, Canvas, 和 SVG。 PhantomJS 能夠用於 頁面自動化 , 網絡監測 , 網頁截屏 ,以及 無界面測試 等。
不少其它的測試框架都是基於PhantomJS二次開發的,例以下面要講的casperjs,nightmare
 
nightmare
 
nightmare是一個高級瀏覽器自動化依賴庫。

var Nightmare = require(‘nightmare’);
var expect = require(‘chai’).expect; // jshint ignore:line

describe('test yahoo search results', function() {
it('should find the nightmare github link first', function*() {
  var nightmare = Nightmare()
  var link = yield nightmare
    .goto('http://yahoo.com')
    .type('form[action*="/search"] [name=p]', 'github nightmare')
    .click('form[action*="/search"] [type=submit]')
    .wait('#main')
    .evaluate(function () {
      return document.querySelector('#main .searchCenterMiddle li a').href
    })
  expect(link).to.equal('https://github.com/segmentio/nightmare');
});
});
1
2
3
4
 
casperjs
 
CasperJS 是一個開源的導航腳本和測試工具,使用 JavaScript 基於 PhantomJS 編寫,用於測試 Web 應用功能,Phantom JS是一個服務器端的 JavaScript API 的 WebKit。其支持各類Web標準: DOM 處理, CSS 選擇器, JSON, Canvas, 和 SVG.

var casper = require(‘casper’).create();
var fs = require(‘fs’)
casper.start(‘https://github.com/login/‘);
casper.waitForSelector(‘input.btn.btn-primary.btn-block’); // wait for the form node to be added
casper.then(function() {
this.fillSelectors(‘.auth-form-body’, {
‘#login_field’: ‘qileilove’,
‘#password’: ‘*
});
this.click(‘input.btn.btn-primary.btn-block’); // Click the login button instead of submitting the form
this.echo(‘Browser Cookie: ‘ + this.evaluate(function() {
return document.cookie;
}));

casper.run(function() {
  var cookies = JSON.stringify((this.page.cookies));
  fs.write('cookie.txt', cookies, 'w');
  this.exit();
});
casper.wait(3000); // Wait for ajax form submission
casper.then(function() {
  this.capture('logged-in.png')
});

casper.run();
1
2
3
4
5
6
 
## visual regression-test
 
backstopjs
 
BackstopJS 是自動 CSS 迴歸測試工具,它經過比較不一樣視窗大小的 DOM 截圖來回應你所測試的 Web 界面。能夠識別出兩個不一樣視角上的網頁差別。
"scenarios": [
  {
    "label": "My Local Test",
    "url": "../../index.html",
    "hideSelectors": [],
    "removeSelectors": [
    ],
    "selectors": [
      "nav",
      ".jumbotron",
      "body .col-md-4:nth-of-type(1)",
      "body .col-md-4:nth-of-type(2)",
      "body .col-md-4:nth-of-type(3)",
      "footer"
    ],
    "readyEvent": null,
    "delay": 0,
    "onReadyScript": null,
    "onBeforeScript": null
  }
],
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
 
viff
我們公司的 基於selenium的,已經廢了。。。 2年多沒更新了
 
 
success
 
Succss is a command line tool built to find image-based differences between website updates. Succss relies on npm and is installed globally.
https://github.com/B2F/Succss
也一年沒更新了..
 
 
phantomcss
 
PhantomCSS 是 CSS 迴歸測試工具。一個經過 PhantomJS 或者 SlimerJS 和 Resemble.js 進行自動視覺迴歸測試的 CasperJS 模塊。
casper.
    start( url ).
    then(function(){        
// do something
        casper.click('button#open-dialog');        
// Take a screenshot of the UI component
        phantomcss.screenshot('#the-dialog', 'a screenshot of my dialog');

    });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
##JavaScript驗證工具
eslint
 
jshint
 
jslint
 
三者比較的文章
https://www.sitepoint.com/comparison-javascript-linting-tools/
 
## 前端mock工具
 
Mock.js
 
 Mockjs是個可以攔截頁面ajax請求並模擬返回數據的小工具,藉助Mockjs,前端開發中在後臺測試接口尚未給的時候就能夠本身攔截請求模擬數據進行愉快的開發了,因此只要制定好了協議,先後端分離開發的成本能夠降到基本爲0,也不須要聯調工具了。
 
sinon.js
爲Javascript提供獨立的spies,stubs和mocks。沒有任何依賴,能夠與任何單元測試框架協同工做。
 
 
## api測試工具
SuperTest
 
基於SuperAgent ,提供對HTTP測試的高度抽象.
能嵌入各種測試框架,提供語義良好的斷言.
var app = require('../app');
var request = require('supertest');

describe('router testing', function () {
    it('site root response', function (done) {
        request(app)
            .get('/')
            .expect('Content-Type', 'text/html; charset=utf-8')
            .expect(200)
            .end(function(err, res){
                if (err) throw err;
                done();
            });
    });

```利用Mocha + Chai + SuperTest就能夠搭建一套 前端rest-api測試框架

相關文章
相關標籤/搜索