chai.js 断言库简单实现

杨军军

最近研究一下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
阅读 1.7k

1.1k 声望
25 粉丝
0 条评论
1.1k 声望
25 粉丝
文章目录
宣传栏