前端测试 前端测试工具集锦

seven qa · 2016年06月17日 · 最后由 Summer Gan 回复于 2019年04月26日 · 3005 次阅读

总结最近了解的前端测试的相关内容,发现前端这里真的是太庞大了,而且各种测试工具层出不穷,需要总结东西太多了,如有遗漏请大家见谅。

TDD vs BDD:

TDD 与 BDD 概念不再描述了,直奔主题。

前端 BDD 测试框架

jasmine
Installation

npm install -g jasmine

Initializing
To initialize a project for Jasmine

jasmine init

To seed your project with some examples

jasmine examples

Usage
To run your test suite

jasmine
describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
  });
});

mocha(推荐,简洁明了)

Installation

Install with npm:

$ npm install -g mocha

Getting Started

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

In your editor:

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:

$  mocha

  .

  ✔ 1 test complete (1ms)

前端 TDD 测试框架

Qunit
Installation

$ npm i qunit

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

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;

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);
  });
});

Add the following to your package.json:

"scripts": {
  "test": "jest"
}

Run npm test:

[PASS] __tests__/sum-test.js (0.010s)

代码覆盖率工具

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

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();
};

当涉及异步调用时,基于链式的队列是个糟糕的模式

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');
});

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!');
  });
});

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');
    });
    });

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();

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
  }
],

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');

    });

##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 测试框架

共收到 5 条回复 时间 点赞

不太全

#1 楼 @lihuazhang 基本目前主流的,工具太多,一个一个介绍也没必要

不错,一直在用 Casperjs 做监控

请教 Phantomcss 的使用有什么资料么

puppeteer selenium 都是常见的

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册