前言
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