Mocha

Mocha

https://mochajs.org/#installation

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.

Assert API

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

Describe it

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

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

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均为字符串,字符串比较出错时则控制台会用颜色把相异的部分标出来。

Hooks

https://mochajs.org/#hooks

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).

自己动手

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.

猜你喜欢

转载自www.cnblogs.com/lightsong/p/9452464.html