javascript
JavaScript中不得不说的断言?
斷言主要應用于“調試”與“測試”
一、前端中的斷言
仔細地查找一下JavaScript中的API,實際上并沒有多少關于斷言的方法。唯一一個就是console.assert:
// console.assert(condition, message)const a = '1'console.assert(typeof a === 'number', 'a should be Number')當condition為false時,該方法則會將錯誤消息寫入控制臺。如果為true,則無任何反應。
實際上,很少使用console.assert方法,如果你閱讀過vue或者vuex等開源項目,會發現他們都定制了斷言方法:
// Vuex源碼中的工具函數function assert (condition, msg) {if (!condition) {throw new Error(`[Vuex] ${msg}`)}}二、Node中的斷言
Node中內置斷言庫(assert),這里我們可以看一個簡單的例子:
try {assert(false, '這個值應該是true')} catch(e) {console.log(e instanceof assert.AssertionError) // trueconst { actual, expected, operator } = econsole.log(`實際值: ${actual},期望值: ${expected}, 使用的運算符:${operator}`)// 實際值: false,期望值: true, 使用的運算符:==}assert模塊提供了不少的方法,例如strictEqual、deepStrictEqual、notDeepStrictEqual等,仔細觀察這幾個方法,我們又得來回顧一下JavaScript中的相等比較算法:
- 抽象相等比較算法 (==)
- 嚴格相等比較算法 (===)
- SameValue (Object.is())
- SameValueZero
幾個方法的區別可以查看這可能是你學習ES7遺漏的知識點。
在Node10.2.0文檔中你會發現像assert.equal、assert.deepEqual這樣的api已經被廢除,也正是避免==的復雜性帶來的易錯性。而保留下來的api基本上多是采用后幾種算法,例如:
- strictEqual使用了嚴格比較算法
- deepStrictEqual在比較原始值時采用SameValue算法
三、chai.js
從上面的例子可以發現,JavaScript中內置的斷言方法并不是特別的全面,所以這里我們可以選擇一些三方庫來滿足我們的需求。
這里我們可以選擇chai.js,它支持兩種風格的斷言(TDD和BDD):
const chai = require('chai')const assert = chai.assertconst should = chai.should()const expect = chai.expectconst foo = 'foo'// TDD風格 assertassert.typeOf(foo, 'string')// BDD風格 shouldfoo.should.be.a('string')// BDD風格 expectexpect(foo).to.be.a('string')大部分人多會選擇expect斷言庫,的確用起來感覺不錯。具體可以查看官方文檔,畢竟確認過眼神,才能選擇適合的庫。
四、expect.js源碼分析
expect.js不僅提供了豐富的調用方法,更重要的就是它提供了類似自然語言的鏈式調用。
鏈式調用
談到鏈式調用,我們一般會采用在需要鏈式調用的函數中返回this的方法實現:
class Person {constructor (name, age) {this.name = namethis.age = age}updateName (val) {this.name = valreturn this}updateAge (val) {this.age = valreturn this}sayHi () {console.log(`my name is ${this.name}, ${this.age} years old`)}}const p = new Person({ name: 'xiaoyun', age: 10 })p.updateAge(12).updateName('xiao ming').sayHi()然而在expect.js中并不僅僅采用這樣的方式實現鏈式調用,首先我們要知道expect實際上是Assertion的實例:
function expect (obj) {return new Assertion(obj)}接下來看核心的Assertion構造函數:
function Assertion (obj, flag, parent) {this.obj = obj;this.flags = {};// 通過flags記錄鏈式調用用到的那些標記符,// 主要用于一些限定條件的判斷,比如not,最終返回結果時會通過查詢flags中的not是否為true,來決定最終返回結果if (undefined != parent) {this.flags[flag] = true;for (var i in parent.flags) {if (parent.flags.hasOwnProperty(i)) {this.flags[i] = true;}}}// 遞歸注冊Assertion實例,所以expect是一個嵌套對象var $flags = flag ? flags[flag] : keys(flags), self = this;if ($flags) {for (var i = 0, l = $flags.length; i < l; i ) {// 避免進入死循環if (this.flags[$flags[i]]) {continue}var name = $flags[i], assertion = new Assertion(this.obj, name, this)// 這里要明白修飾符中有一部分也是Assertion原型上的方法,例如 an, be。if ('function' == typeof Assertion.prototype[name]) {// 克隆原型上的方法var old = this[name];this[name] = function () {return old.apply(self, arguments);};// 因為當前是個函數對象,你要是在后面鏈式調用了Assertion原型上方法是找不到的。// 所以要將Assertion原型鏈上的所有的方法設置到當前的對象上for (var fn in Assertion.prototype) {if (Assertion.prototype.hasOwnProperty(fn) && fn != name) {this[name][fn] = bind(assertion[fn], assertion);}}} else {this[name] = assertion;}}}}為什么要這樣設計?我的理解是:首先expect.js的鏈式調用充分的體現了調用的邏輯性,而這種嵌套的結構真正的體現了各個修飾符之間的邏輯性。
所以我們可以這樣書寫:
const student = {name: 'xiaoming',age: 20}expect(student).to.be.a('object')當然這并沒有完,對于每一個Assertion原型上的方法多會直接或者間接的調用assert方法:
Assertion.prototype.assert = function (truth, msg, error, expected) {// 這就是flags屬性的作用之一var msg = this.flags.not ? error : msg, ok = this.flags.not ? !truth : truth, err;if (!ok) {// 拋出錯誤err = new Error(msg.call(this));if (arguments.length > 3) {err.actual = this.obj;err.expected = expected;err.showDiff = true;}throw err;}// 為什么這里要再創建一個Assertion實例?也正是由于expect實例是一個嵌套對象。this.and = new Assertion(this.obj);};并且每一個Assertion原型上的方法最終通過返回this來實現鏈式調用。所以我們還可以這樣寫:
expect(student).to.be.a('object').and.to.have.property('name')到此你應該已經理解了expect.js的鏈式調用的原理,總結起來就是兩點:
- 原型方法還是通過返回this,實現鏈式調用;
- 通過嵌套結構的實例對象增強鏈式調用的邏輯性;
所以我們完全可以這樣寫:
// 強烈不推薦 不然怎么能屬于BDD風格呢?expect(student).a('object').property('name')????喜歡本文的小伙伴們,歡迎關注我的訂閱號超愛敲代碼,查看更多內容.
總結
以上是生活随笔為你收集整理的JavaScript中不得不说的断言?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [JSConf EU 2018] 大脑控
- 下一篇: 起点海外版 Hybrid App-内嵌页