使用Jasmine測試你的Javascript(一)之 Jasmine簡介
使用Jasmine測試你的Javascript(二)之 Suites和specs
通過前兩篇我們已經基本可以簡單的用jasmine寫出一段測試代碼,本篇我們將來繼續介紹jasmine中的matchers。
Jasmine提供了一些內置的matchers(匹配器)供你使用,下面有幾個是你會經常用到的。
expect(x).toEqual(y);
當x和y相等時候通過
expect(x).toBe(y);
當x和y是同一個對象時候通過
expect(x).toMatch(pattern);
x匹配pattern(字符串或正則表達式)時通過
expect(x).toBeDefined();
x不是undefined時通過
expect(x).toBeUndefined();
x
是undefined時通過
expect(x).toBeNull();
x是null時通過
expect(x).toBeTruthy();
x和true等價時候通過
expect(x).toBeFalsy();
x和false等價時候通過
expect(x).toContain(y);
x(數組或字符串)包含y時通過
expect(x).toBeLessThan(y);
x小於y時通過
expect(x).toBeGreaterThan(y);
x大於y時通過
expect(function(){fn();}).toThrow(e);
函數fn拋出異常時候通過
舊版本中的一些matchers(匹配器)
toNotEqual
,toNotBe
,toNotMatch
,toNotContain
將在以后被廢除.建議使用not.toEqual
,not.toBe
,not.toMatch
, andnot.toContain
respectively.
所有的matchers匹配器支持添加
.not反轉結果:
expect(x).not.toEqual(y);
自定義Matchers(匹配器)
以上提供的Matchers(匹配器)已經可以滿足你的大部分需求了,但是我們仍然推薦你按照需求定義自己的匹配器去匹配更加復雜的情況,自定義匹配器可以使你的代碼意圖更加明了,並且可以幫你移除重復的代碼。
自定義(matchers)匹配器是一件很簡單的事件,一個matcher(匹配器)函數使用 this.actual 接收到一個實際值,並且該匹配函數也可以包括0或多個參數。當實際值通過匹配器的匹配,你應當返回一個ture否則返回false。
以下代碼定義了一個名為
toBeLessThan()的匹配器
:
toBeLessThan: function(expected) {
return this.actual < expected;
};
將匹配器添加到suite中, 在before或者it代碼塊內調用
this.addMatchers()
beforeEach(function() {
this.addMatchers({
toBeLessThan: function(expected) {
return this.actual < expected;
}
});
});
你可以自定義匹配失敗的消息,在匹配函數中給this.message賦值即可實現
beforeEach(function() {
this.addMatchers({
toBeLessThan: function(expected) {
var actual = this.actual;
var notText = this.isNot ? " not" : "";
this.message = function () {
return "Expected " + actual + notText + " to be less than " + expected;
}
return actual < expected;
}
});
});