为了账号安全,请及时绑定邮箱和手机立即绑定

mocha get started入门学习总结

simple, flexible, fun
features
  • browser support
  • simple async support, including promises
  • test coverage reporting
  • string diff support
  • javascript API for running tests
  • proper exit status for CI support etc
  • auto-detects and disables coloring for non-ttys
  • maps uncaught exceptions to the correct test case
  • async test timeout support
  • test retry support
  • test-specific timeouts
  • growl notification support
  • reports test durations
  • highlights slow tests
  • file watcher support
  • global variable leak detection
  • optionally run tests that match a regexp
  • auto-exit to prevent “hanging” with an active loop
  • easily meta-generate suites & test-cases
  • mocha.opts file support
  • clickable suite titles to filter test execution
  • node debugger support
  • detects multiple calls to done()
  • use any assertion library you want
  • extensible reporting, bundled with 9+ reporters
  • extensible test DSLs or “interfaces”
  • before, after, before each, after each hooks
  • arbitrary transpiler support (coffee-script etc)
  • TextMate bundle
测试脚本概念
  • 测试源码的脚本,Mocha的作用是运行测试脚本.测试脚本里面应该包括一个或多个describe块,每个describe块应该包括一个或多个it块
  • escribe块称为"测试套件"(test suite),表示一组相关的测试
  • it块称为"测试用例"(test case),表示一个单独的测试,是测试的最小单位
  • 断言: 判断源码的实际执行结果与预期结果是否一致,如果不一致就抛出一个错误。expect断言的优点是很接近自然语言。如果expect断言不成立,就会抛出一个错误。事实上,只要不抛出错误,测试用例就算通过。
    it('1 加 1 应该等于 2', function() {});

Installation

$ npm install --global mocha
$ npm install --save-dev mocha

Getting Started

$ npm install mocha
$ mkdir test
$ $EDITOR test/test.js # or open with your favorite editor
//write...
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));
    });
  });
});

Assertions

using Node.js’ built-in assert module–but generally, if it throws an Error, it will work! This means you can use libraries such as:

should.js - BDD style shown throughout these docs
expect.js - expect() style assertions
chai - expect(), assert() and should-style assertions
better-assert - C-style self-documenting assert()
unexpected - “the extensible BDD assertion toolkit”

Asynchronous Code 异步代码

By adding a callback (usually named done) to it(), Mocha will know that it should wait for this function to be called to complete the test.

describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(done);
});
});
});
  • WORKING WITH PROMISES *
    This is useful if the APIs you are testing return promises instead of taking callbacks:
    beforeEach(function() {
    return db.clear()
    .then(function() {
    return db.save([tobi, loki, jane]);
    });
    });
    describe('#find()', function() {
    it('respond with matching records', function() {
    return db.find({ type: 'User' }).should.eventually.have.length(3);
    });
    });

Synchronous Code

When testing synchronous code, omit(忽略) the callback and Mocha will automatically continue on to the next test.

describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
[1,2,3].indexOf(5).should.equal(-1);
[1,2,3].indexOf(0).should.equal(-1);
});
});
});

Arrow Functions

Passing arrow functions (“lambdas”) to Mocha is discouraged.

Hooks

With its default “BDD”-style interface, Mocha provides the hooks before(), after(), beforeEach(), and afterEach(). These should be used to set up preconditions and clean up after your tests.


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

//all hooks run (once)
});

* DESCRIBING HOOKS *

beforeEach(function() {
// beforeEach hook
});

beforeEach(function namedFun() {
// beforeEach:namedFun
});

beforeEach('some description', function() {
// beforeEach:some description
});

### Pending(挂起的) Tests
> “Pending”–as in “someone should write these test cases eventually”–test-cases are simply those without a callback:

describe('Array', function() {
describe('#indexOf()', function() {
// pending test below
it('should return -1 when the value is not present');
});
});

### Exclusive(排他性) Tests

describe('Array', function() {
describe.only('#indexOf()', function() {
// ...
});
});

Inclusive(兼容性) Tests

describe('Array', function() {
describe.skip('#indexOf()', function() {
// ...
});
});

### Retry Tests
> It’s not recommended to use this feature for unit tests.
### Dynamically Generating Tests

var assert = require('chai').assert;

function add() {
return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
return prev + curr;
}, 0);
}

describe('add()', function() {
var tests = [
{args: [1, 2], expected: 3},
{args: [1, 2, 3], expected: 6},
{args: [1, 2, 3, 4], expected: 10}
];

tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
});

### Timeouts
> Suite-level timeouts may be applied to entire test “suites”, or disabled via this.timeout(0). 

describe('a suite of tests', function() {
this.timeout(500);

it('should take less than 500ms', function(done){
setTimeout(done, 300);
});

it('should take less than 500ms as well', function(done){
setTimeout(done, 250);
});
})


### Diffs
> Mocha will attempt to display the difference between what was expected, and what the assertion actually saw.

### Usage
> Mocha’s “interface” system allows developers to choose their style of DSL. Mocha has BDD, TDD, Exports, QUnit and Require-style interfaces.

1. BDD
> The BDD interface provides describe()==context(), it()==specify(), before(), after(), beforeEach(), and afterEach().

describe('Array', function() {
before(function() {
// ...
});

describe('#indexOf()', function() {
  context('when not present', function() {
    it('should not throw an error', function() {
      (function() {
        [1,2,3].indexOf(4);
      }).should.not.throw();
    });
    it('should return -1', function() {
      [1,2,3].indexOf(4).should.equal(-1);
    });
  });
  context('when present', function() {
    it('should return the index where the element first appears in the array', function() {
      [1,2,3].indexOf(3).should.equal(2);
    });
  });
});

});

2. TDD
> The TDD interface provides suite(), test(), suiteSetup(), suiteTeardown(), setup(), and teardown():

suite('Array', function() {
setup(function() {
// ...
});

suite('#indexOf()', function() {
test('should return -1 when not present', function() {
assert.equal(-1, [1,2,3].indexOf(4));
});
});
});

3. Exports
> The Exports interface is much like Mocha’s predecessor expresso. The keys before, after, beforeEach, and afterEach are special-cased, object values are suites, and function values are test-cases:

module.exports = {
before: function() {
// ...
},

'Array': {
'#indexOf()': {
'should return -1 when not present': function() {
[1,2,3].indexOf(4).should.equal(-1);
}
}
}
};


4. Qunit
> The QUnit-inspired interface matches the “flat” look of QUnit, where the test suite title is simply defined before the test-cases. Like TDD, it uses suite() and test(), but resembling BDD, it also contains before(), after(), beforeEach(), and afterEach().

5. Require
> The require interface allows you to require the describe and friend words directly using require and call them whatever you want. This interface is also useful if you want to avoid global variables in your tests.

###Interfaces
### Reporters
> Mocha reporters adjust to the terminal window, and always disable ANSI-escape coloring when the stdio streams are not associated with a TTY.
### Running Mocha in the Browser
> Mocha runs in the browser. Every release of Mocha will have new builds of ./mocha.js and ./mocha.css for use in the browser.

### mocha.opts
### The test/ Directory
### Editor Plugins
### Examples
### Testing Mocha
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
7244
获赞与收藏
3476

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消