Angular单元测试

498 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

单元测试

单元测试又叫单测,是为了保证我们的代码指令,避免代码中出现bug的一种测试方式。

ng6内置了单测,通过jestmine工具进行测试

jestmine写描述不支持中文。

进入测试,执行 ng test指令即可

describe

定义整体测试描述的方法

第一个参数表示描述

第二个参数是一个函数,在函数中我们进行测试

it

定义单元测试方法

第一个参数表示测试功能点

第二个参数是函数,在里面我们定义断言方法

expect

定义断言方法

参数就是断言表达式,

方法执行完毕,我们判断结果

断言方法

toBe        

类似于`===`       

expect(true).toBe(true);

toEqual

比较变量字面量的值   

expect({ foo: 'foo'}).toEqual( {foo: 'foo'} );

toMatch

匹配值与正则表达式   

expect('foo').toMatch(/foo/);

toBeDefined

检验变量是否定义

var foo = {

    bar: 'foo'

};

expect(foo.bar).toBeDefined();

toBeNull

检验变量是否为`null`

var foo = null;

expect(foo).toBeNull();

toBeTruthy

检查变量值是否能转换成布尔型`真`值

expect({}).toBeTruthy();

toBeFalsy

检查变量值是否能转换成布尔型`假`值

expect('').toBeFalsy();

toContain

检查在数组中是否包含某个元素

expect([1,2,4]).toContain(1);

toBeLessThan

检查变量是否小于某个数字

expect(2).toBeLessThan(10);

toBeGreaterThan

检查变量是否大于某个数字或者变量

expect(2).toBeGreaterThan(1);

toBeCloseTo

比较两个数在保留几位小数位之后,是否相等,用于数字的精确比较

expect(3.1).toBeCloseTo(3, 0);

toThrow

检查一个函数是否会throw异常

expect(function(){ return a + 1;}).toThrow();  // true

expect(function(){ return a + 1;}).not.toThrow(); // false

toHaveBeenCalled

检查一个监听函数是否被调用过

toHaveBeenCalledWith

检查监听函数调用时的参数匹配信息