快速掌握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();