转自:http://www.ruanyifeng.com/blog/2015/12/a-mocha-tutorial-of-examples.html
上面的测试脚本里面,有一句断言。
expect(add(1, 1)).to.be.equal(2);
所谓"断言",就是判断源码的实际执行结果与预期结果是否一致,如果不一致就抛出一个错误。上面这句断言的意思是,调用add(1, 1)
,结果应该等于2。
所有的测试用例(it块)都应该含有一句或多句的断言。它是编写测试用例的关键。断言功能由断言库来实现,Mocha本身不带断言库,所以必须先引入断言库。
var expect = require('chai').expect;
断言库有很多种,Mocha并不限制使用哪一种。上面代码引入的断言库是chai
,并且指定使用它的expect
断言风格。
expect
断言的优点是很接近自然语言,下面是一些例子。
// 相等或不相等 expect(4 + 5).to.be.equal(9); expect(4 + 5).to.be.not.equal(10); expect(foo).to.be.deep.equal({ bar: 'baz' }); // 布尔值为true expect('everthing').to.be.ok; expect(false).to.not.be.ok; // typeof expect('test').to.be.a('string'); expect({ foo: 'bar' }).to.be.an('object'); expect(foo).to.be.an.instanceof(Foo); // include expect([1,2,3]).to.include(2); expect('foobar').to.contain('foo'); expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); // empty expect([]).to.be.empty; expect('').to.be.empty; expect({}).to.be.empty; // match expect('foobar').to.match(/^foo/);
基本上,expect
断言的写法都是一样的。头部是expect
方法,尾部是断言方法,比如equal
、a
/an
、ok
、match
等。两者之间使用to
或to.be
连接。
如果expect
断言不成立,就会抛出一个错误。事实上,只要不抛出错误,测试用例就算通过。
it('1 加 1 应该等于 2', function() {});
上面的这个测试用例,内部没有任何代码,由于没有抛出了错误,所以还是会通过。