好玩儿的expect

前言

1> 借鉴里面的应用思想,使用断言提升代码的健壮性及维护性

2> 实现方式——不采用直接嵌入expect的方式,统一进行重写(提取经常使用断言方法,从新构造API)

官网介绍

https://github.com/LearnBoost/expect.jshtml

在这里,主要是熟悉里面的API便可.列举一下经常使用的几项——前端

1> 布尔(ok)git

var bFlag = true;       

// 判断布尔类型
expect(bFlag).to.be.ok();   // 经过

2> 全等(be/equal)github

expect(NaN).not.to.equal(NaN);  // 经过
expect(NaN).not.to.be(NaN); // 经过

3> 非全等(eql)编程

expect(1).to.eql('1');  // 经过

// 比较对象内容
expect({ a: 'b' }).to.eql({ a: 'b' });  // 经过

4> 类型数组

// typeof with optional `array`
expect(5).to.be.a('number');
expect([]).to.be.an('array');  // works
expect([]).to.be.an('object'); // works too, since it uses `typeof`

// constructors
expect(5).to.be.a(Number);
expect([]).to.be.an(Array);
expect(tobi).to.be.a(Ferret);
expect(person).to.be.a(Mammal);

5> 长度(length)函数

expect([]).to.have.length(0);
expect([1,2,3]).to.have.length(3);

6> 空性能

expect({ my: 'object' }).to.not.be.empty();
expect([1,2,3]).to.not.be.empty();

7> 属性this

expect({a: 'b'}).to.have.property('a');
expect({ a: 'b' }).to.have.key('a');
expect({ a: 'b', c: 'd' }).to.only.have.keys(['a', 'c']);

应用场合

expect主要是为前端js实现断言。是防护性编程(请参考里面的assert断言)内容的一部分。url

主要的表现形式注入到函数(或者组件)的参数的极限值的判断及处理。

例如,如下下载组件暴露的download接口,须要对传入的opts参数作判断——

var download = function(opts) {
    var list = opts.list;

    // 接收的参数必须是一个数组
    expect(list).to.be.an('array');

    var file = list[0];

    // file不能为空
    expect(file).to.not.empty();

    // 接收的file对象必须具备属性size且为数字
    expect(file).to.have.property('size');
    expect(file.size).to.be.a('number');

    // 接收的file对象必须具备属性size且为数字
    expect(file).to.have.property('isdir');
    expect(file.isdir).to.be.a('number');

    // 单文件下载
    // 即:数组只有一个对象
    if (list.length === 1) {

        // 直接单文件下载方式
        if ((file.isdir === 0) {
            this._downloadOneFileDlink(file);
        } else if (file.isdir === 1) {
            // 文件夹
            this._downloadPackage(list);
        }

        return;
    }

    // 打包下载
    this._downloadPackage(list);

    return;
}

主要优点

相比于注释及日志记录的方式,expect(断言)的使用有如下两点优点——

  • 异常抛出——可以实时定位问题,助于加速定位问题
  • 代码简洁易懂——可以清晰明白接口调用须要的参数类型及范围等,利于代码维护及继承

实现方案

开发阶段,可直接使用该库,使用expect类进行断言处理。或对其中核心方法从新构造以实现对应核心应用便可(构造Assert类,加入经常使用断言方法)。在产品部署阶段,过滤断言语句,以提升执行性能。

相关文章
相关标签/搜索