共计 1059 个字符,预计需要花费 3 分钟才能阅读完成。
最近研究一下 Chai, 发现其示例代码挺有意思的,就自己实现一下,
官方示例:
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);
简单实现上面代码功能:
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
正文完