最近研究一下Chai, 發現其示例代碼挺有意思的,就本身實現一下,this
官方示例:code
var expect = chai.expect; expect(foo).to.be.a('string'); expect(foo).to.equal('bar'); expect(foo).to.have.lengthOf(3); expect(tea).to.have.property('flavors') .with.lengthOf(3);
簡單實現上面代碼功能:get
const expect = (source, errMsg = 'Error') => { const equal = (target) => { if (source !== target) { throw new Error(errMsg) } else { return { to: to } } } const be = { a (target) { if (typeof source !== target) { throw new Error(errMsg) } else { return { to: to } } } } const haveFactory = (source) => { return { lengthOf (target) { if (source.length !== target) { throw new Error(`${errMsg}: actual: ${source.length}, expect: ${target}`) } else { return { with: this, to: to } } }, property (target) { if (!source.hasOwnProperty(target)) { throw new Error(errMsg) } else { return { with: haveFactory(source[target]), to: to } } } } } const to = { equal, be, have: haveFactory(source, errMsg) } return { to } } const foo = 'bar' const tea = { flavors: 'abcd' } try { expect(foo).to.be.a('string'); expect(foo).to.equal('bar'); expect(foo).to.have.lengthOf(3); expect(tea).to.have.property('flavors').with.lengthOf(3); } catch (error) { console.log(error.message) } // output // Error: actual: 4, expect: 3