Mocha

Mocha

https://mochajs.org/#installationhtml

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.node

 

Assert API

https://nodejs.org/api/assert.htmlgit

 

 

Describe it

https://cnodejs.org/topic/516526766d38277306c7d277web

如下为最简单的一个mocha示例:api

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(5)); assert.equal(-1, [1,2,3].indexOf(0)); }) }) });
  • describe (moduleName, testDetails) 由上述代码可看出,describe是能够嵌套的,好比上述代码嵌套的两个describe就能够理解成测试人员但愿测试Array模块下的#indexOf() 子模块。module_name 是能够随便取的,关键是要让人读明白就好。
  • it (info, function) 具体的测试语句会放在it的回调函数里,通常来讲info字符串会写指望的正确输出的简要一句话文字说明。当该it block内的test failed的时候控制台就会把详细信息打印出来。通常是从最外层的describe的module_name开始输出(能够理解成沿着路径或者递归链或者回调链),最后输出info,表示该指望的info内容没有被知足。一个it对应一个实际的test case
  • assert.equal (exp1, exp2) 断言判断exp1结果是否等于exp2, 这里采起的等于判断是== 而并不是 === 。即 assert.equal(1, ‘1’) 认为是True。这只是nodejs里的assert.js的一种断言形式,下文会提到一样比较经常使用的should.js。

若是exp1和exp2均为字符串,字符串比较出错时则控制台会用颜色把相异的部分标出来。app

 

Hooks

https://mochajs.org/#hooksless

 

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

Tests can appear before, after, or interspersed with your hooks. Hooks will run in the order they are defined, as appropriate; all before() hooks run (once), then any beforeEach() hooks, tests, any afterEach() hooks, and finally after() hooks (once).async

 

本身动手

https://github.com/fanqingsong/code-snippet/tree/master/web/mocha_test函数

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

 

 

与TDD区别

https://stackoverflow.com/questions/4395469/tdd-and-bdd-differences

27 down vote

BDD is from customers point of view and focuses on excpected behavior of the whole system.

TDD is from developpers point of view and focuses on the implementation of one unit/class/feature. It benefits among others from better architecture (Design for testability, less coupling between modules).

From technical point of view (how to write the "test") they are similar.

I would (from an agile point of view) start with one bdd-userstory and implement it using TDD.

相关文章
相关标签/搜索