@garygchai
2017-02-17T09:49:17.000000Z
字数 2092
阅读 2072
自动化测试
运营后台项目的ui自动化测试是基于 egg 的单元测试下面开发的,所以只需要额外安装 nightmare 即可,至于 egg-bin、mocha 直接使用原有就行。
安装 nightmare
$ cd yoda-xiss & npm install nightmare --save-dev
文档胜过前言万语:https://mochajs.org/
安装
$ npm i mocha --save-dev
举例
var assert = require('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(4));});});});
describe 用于描述一组或单个测试用例,it 描述单个测试用例,assert 用于做断言。
执行结果
$ ./node_modules/mocha/bin/mochaArray#indexOf()✓ should return -1 when the value is not present1 passing (9ms)
上面用到的 assert 就是断言库中的一种,在 mocha 中,我们可以任意选择断言库:
should.js - 行为测试的方式
expect.js - 使用 expect() 的方式
chai - 支持expect(), assert() 和 should 等方式断言
单元测试用例通常也会执行异步的代码,在 mocha 中通过 done() 方法通知 mocha 方法执行结束。
describe('User', function() {describe('#save()', function() {it('should save without error', function(done) {var user = new User('Luna');user.save(function(err) {if (err) done(err);else done();});});});});
before() - 所有的用例执行之前执行 after() - 所有的用例执行之后执行 beforeEach() - 每个用例执行之前执行 afterEach() - 每个用例执行之后执行
describe('hooks', function() {before(function() {// runs before all tests in this block});after(function() {// runs after all tests in this block});beforeEach(function() {// runs before each test in this block});afterEach(function() {// runs after each test in this block});// test cases});
以上是 mocha 常用的功能,更多用法请参考文档。
一言不合上文档:https://github.com/segmentio/nightmare
$ npm install nightmare --save-dev我们就把 nightmare 当做一个异步执行的方法,在 nightmare 执行结束或者出错调用一下 mocha 的 done() 方法就完成完成 nightmare 的执行。
Example:
var Nightmare = require('nightmare');var expect = require('chai').expect; // jshint ignore:linedescribe('test duckduckgo search results', function() {it('should find the nightmare github link first', function(done) {var nightmare = Nightmare()nightmare.goto('https://duckduckgo.com').type('#search_form_input_homepage', 'github nightmare').click('#search_button_homepage').wait('#zero_click_wrapper .c-info__title a').evaluate(function () {return document.querySelector('#zero_click_wrapper .c-info__title a').href}).end().then(function(link) {expect(link).to.equal('https://github.com/segmentio/nightmare');done();})});});
运行
$ mocha