快速掌握Jasmine語法
學習Jasmine記住四個核心的概念即可:分組、用例、期望、匹配。
四個核心概念分別對應Jasmine的四種函數,簡要說明如下:
describe(string,function)這個函數表示分組,也就是一組測試用例。
it(string,function)這個函數表示測試用例。
expect(expression)表示期望expression這個表達式具有某個值或者具有某種行爲。
to***(arg)這個函數表示匹配。
內置的匹配函數解析
- 在當前最新的版本中,Jasmine內置了15個匹配函數,列表如下:
toBe()
toBeDefined()
toBeUndefined()
toBeNull()
toBeTruthy()
toBeFalsy()
toEqual()
toBeLessThan()
toBeGreaterThan()
toContain()
toBeCloseTo()
toHaveBeenCalled()
toHaveBeenCalledWith()
toMatch()
toThrow()
- toContain()用來檢測數組中是否包含某個元素:
var a = ['foo', 'bar', 'baz'];
expect(a).toContain('bar');
- toBeCloseTo 基本的功能是,把兩個數按照指定的精度都進行四捨五入,然後比較是否相等:
var pi = 3.1415926, e = 2.78;
expect(pi).not.toBeCloseTo(e, 2);
expect(pi).toBeCloseTo(e, 0);
(pi取兩位小數位是3.14,e則是2.78,兩者不相等;pi取0位小數是3,e四捨五入是3,兩者相等)
- toMatch() 用來對字符串進行正則匹配。
expect(message).toMatch(/bar/);
- toThrow() 用來匹配某個方法是否會拋出異常。
expect(bar).toThrow();