之前写过一个javascript的语法自测(数组),开头关注作者出的题目,然后我发现可以学一下她的代码,当作测试入门。
  基础概念
  TDD和BDD

  TDD是测试驱动开发,BDD是行为驱动开发
  断言
  node自带的断言库是assert,然后chai.js还提供了别的断言库
  测试框架
  组织测试的框架,比较有名的是Mocha
  一个是Mocha是一个富特征的Javascript全栈测试框架
  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.
  简单实例
  安装

  可以全局安装
  $ npm install --global mocha
  也可以在项目工程中安装
  $ npm install --save-dev mocha
  测试代码
  新建一个test文件夹,在test文件夹下面新建test.js,输入以下内容
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));
})
})
})
  其实assert是断言库,断言库一般用来做判断,这里用了assert.equal来判断程序的结果和期望值是否相等。
  assert的方法很少,也挺直观的
assert.fail(actual, expected, message, operator)
assert.ok(value, [message])
assert.equal(actual, expected, [message])
assert.notEqual(actual, expected, [message])
assert.deepEqual(actual, expected, [message])
assert.notDeepEqual(actual, expected, [message])
assert.strictEqual(actual, expected, [message])
assert.notStrictEqual(actual, expected, [message])
assert.throws(block, [error], [message])
assert.doesNotThrow(block, [error], [message])
assert.ifError(value)
  然后我们看到,代码待用describe(' ',function(){})这样的形式,而且describe可以描述多层结构,利用describe和it的是BDD,句式是描述它应该怎么样的感觉,利用suite和test的是TDD
  运行测试
  在命令行里面输入

  mocha test.js
  然后如下显示,运行时间可能每个人得到的都不一样
  Array
  #indexOf()
  should return -1 when the value is not present
  1 passing (9ms)
  断言库的选择
  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”
  chai支持expect(),assert(),should风格的断言方式,所以chai也是一个比较不错的选择
  关于expet
var expect = require('chai').expect;
describe('arrays', function() {
var a;
beforeEach(function() {
a = [ 1, 2, 3, 4 ];
});
it('you should be able to determine the location of an item in an array', function() {
expect(arraysAnswers.indexOf(a, 3)).to.eql(2);
expect(arraysAnswers.indexOf(a, 5)).to.eql(-1);});
}