初识Jasmine单元测试框架

一个测试栗子
//建立个describe块
describe('JavaScript addition operator',function(){ 
    let arr=[1,2,3,4,5];
    //建立it块
    it('test function sumArray',function(){ 
        //测试函数sumArray返回结果是否为15
        expect(sumArray(arr)).toEqual(15); 
    }); 
});

Suite表示一个测试集,以函数describe(string, function)封装,它包含2个参数:
string:测试组名称,
function:测试组函数。

一个Suite(describe)包含多个Specs(it),一个Specs(it)包含多个断言(expect)

常用的操作函数

Setup在每个测试用例Spec执行之前做一些初始化操作,Teardown在每个Sepc执行完之后做一些清理操作

  • beforeEach():在describe函数中每个Spec执行之前执行
  • afterEach(): 在describe函数中每个Spec数执行之后执行
  • beforeAll():在describe函数中所有的Specs执行之前执行,但只执行一次,在Sepc之间并不会被执行
  • afterAll(): 在describe函数中所有的Specs执行之后执行,但只执行一次,在Sepc之间并不会被执行
常用的Matchers(expect(断言)的比较操作)

一般用来判断返回的结果是否和预期结果一致,返回 True 或 False

expect(sumArray(arr)).toEqual(15); 
  • toEqual():相当于==
  • toNotEqual() 检查变量或属性是否不等于预期值
  • toBe():相当于===
  • toBeDefined():检查变量或属性是否已声明且赋值
  • toBeNull():检查变量或属性是否是null
  • toBeLessThan():数值比较,小于
  • toBeGreaterThan():数值比较,大于
  • toContain():数组中是否包含元素(值)(只能用于数组,不能用于对象)
  • toHaveBeenCalledWith() 判断调用函数时的参数
  • toHaveBeenCalled() : 函数是否被调用
禁用测试

Suites可以被Disabled。在describe函数名之前添加x即可将Suite禁用
被Disabled的Suites在执行中会被跳过,该Suite的结果也不会显示在结果集中


xdescribe('JavaScript addition operator',function(){ 
    let arr=[1,2,3,4,5];
    //建立it块
    it('test function sumArray',function(){ 
        //测试函数sumArray返回结果是否为15
        expect(sumArray(arr)).toEqual(15); 
    }); 
});
挂起Specs

被Pending的Spec不会被执行,但是Spec的名字会在结果集中显示,只是标记为Pending

挂起Specs的方法:

  • 如果在Spec函数it的函数名之前添加x(xit),那么该Spec就会被标记为Pending

  • 一个没有定义函数体的Sepc也会在结果集中被标记为Pending

  • 如果在Spec的函数体中调用pending()函数,那么该Spec也会被标记为Pending。pending()函数接受一个字符串参数,该参数会在结果集中显示在PENDING WITH MESSAGE:之后,作为为何被Pending的原因

describe("unit test sumPrice", function () {
  let inputs;
  beforeEach(function () {
    inputs = [
      {
        barcode: 'ITEM000001',
        name: '雪碧',
        unit: '瓶',
        price: 3.00,
        count: 5
      }
    ];
  });

  xit("should return sumPrice", function () {  //pending
    const sumed = [
      {
        barcode: 'ITEM000001',
        name: '雪碧',
        unit: '瓶',
        price: 3.00,
        count: 5,
        sum: 12,
        save:3
      }
    ];
    expect(sumPrice(inputs)).toEqual(sumed);
  });

  it("can be declared with 'it' but without a function");

  it("should return sumPrice", function () {
    const sumed = [
      {
        barcode: 'ITEM000001',
        name: '雪碧',
        unit: '瓶',
        price: 3.00,
        count: 5,
        sum: 12,
        save:3
      }
    ];
    expect(sumPrice(inputs)).toEqual(sumed);
    pending('this is why it is pending');  //调用pending()函数
  });

});

执行结果:

初识Jasmine单元测试框架_第1张图片

你可能感兴趣的:(初识Jasmine单元测试框架)