文章图例:
学习资料:
测试框架 Mocha 实例教程-阮一峰、Chai.js断言库API中文文档
官网:Chai
“断言”:
就是判断源码的实际执行结果与预期结果是否一致,如果不一致就抛出一个错误。所有的测试用例(it块)都应该含有一句或多句的断言。它是编写测试用例的关键。
断言风格:
- The Expect / Should API covers the BDD assertion styles.
- The Assert API covers the TDD assertion style.
expect:
expect使用链式语言来组织断言。初始化断言使用构造函数来创建断言对象实例,优点是很接近自然语言
var chai = require('chai') ,expect = chai.expect // expect直接指向chai.expect
断言方法:
比如equal、a/an、ok、match等。与expect方法之间使用 to 或 to.be 连接
// 相等或不相等expect(4 + 5).to.be.equal(9);expect(4 + 5).to.be.not.equal(10);expect(foo).to.be.deep.equal({ bar: 'baz' });// 布尔值为trueexpect('everthing').to.be.ok;expect(false).to.not.be.ok;// typeofexpect('test').to.be.a('string');expect({ foo: 'bar' }).to.be.an('object');expect(foo).to.be.an.instanceof(Foo);// includeexpect([1,2,3]).to.include(2);expect('foobar').to.contain('foo');expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');// emptyexpect([]).to.be.empty;expect('').to.be.empty;expect({}).to.be.empty;// matchexpect('foobar').to.match(/^foo/);
语言链:
- to
- be
- been
- is
- that
- which
- and
- has
- have
- with
- at
- of
- same
API:
https://www.chaijs.com/api/bdd/
未解决的、想要实现的效果:
describe('promise - promise测试', function() {it('promise请求测试', function() {return new Promise((res, rej) => {rej(new Error('出错了'))}).then((data) => {expect(data).to.be.a('string')}).catch((err) => {expect(err).to.not.throw(Error) // 期待能判断err是一个错误对象})});});
chai断言拥有多个属性
expect(vm.$props).to.have.property('editorMenus,editorColors')
