在Nodejs项目里写测试

ayli3691 8年前

来自: http://giscafer.com/2016/02/12/nodejs-mocha-test/

不写测试的项目都是耍流氓

BDD和TDD的差别: The Difference Between TDD and BDD

测试框架:

mocha

Mocha是一个基于node.js和浏览器的集合各种特性的Javascript测试框架,并且可以让异步测试也变的简单和> 有趣。Mocha的测试是连续的,在正确的测试条件中遇到未捕获的异常时,会给出灵活且准确的报告。

辅助工具

  • should.js (BDD)
  • chai(支持assert,should,expect)
  • supertest (接口测试,代替浏览器地址请求,十分方便)

一个典型的mocha例子:

var assert = require('chai').assert;  var expect = require('chai').expect;  var should=require('chai').should();      describe('Test', 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    });          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);      });    });  });  })
</div> </div>