expect.js

前言
1> 借鉴里面的应用思想,使用断言提高代码的健壮性及维护性
2> 实现方式——不采用直接嵌入expect的方式,统一进行重写(提取常用断言方法,重新构造API)
官网介绍
https://github.com/LearnBoost/expect.js

在这里,主要是熟悉里面的API即可.列举一下常用的几项——
1> 布尔(ok)

var bFlag = true;       

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

2> 全等(be/equal)

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> 属性

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断言)内容的一部分。

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

例如,以下下载组件暴露的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类,加入常用断言方法)。在产品部署阶段,过滤断言语句,以提高执行性能。
本文转载自:https://www.cnblogs.com/jinguangguo/p/4058385.html

原文地址:https://www.cnblogs.com/smart-girl/p/11048804.html