如何使用Angular 6 / Jasmine对该简单功能进行单元测试

时间:2019-02-13 19:45:27

标签: jasmine angular6 karma-jasmine

我的组件之一具有以下方法。如何为它编写单元测试?

 getInitialSeats() {
    for (let i = 0; i < 100; i++) {
      i = i + 1;
      this.seatObj = {
        seatName: "Seat- " + i,
        seatId: "seat_" + i
      }
      this.totalSeats.push(this.seatObj);
      this.seatObj = {};
      i = i - 1;
    }
  }

1 个答案:

答案 0 :(得分:2)

在编写单元测试之前,我建议您稍微改善一下功能。那里有一些您不一定需要的代码。看看这个功能完全相同的改进功能。

getInitialSeats() {
  for (let i = 1; i <= 100; i++) {
    this.totalSeats.push({
      seatName: "Seat- " + i,
      seatId: "seat_" + i
    });        
  }
}

要测试此功能,我只需要编写一个非常简单的测试用例,就像这样(我假设此功能在组件中):

it('should test the initial seats generation', () => {
  // test the before state, i assume the array will be empty beforehand
  expect(component.totalSeats.length).toBe(0);

  // invoke the function
  component.getInitialSeats();

  // test the amount of seats generated
  expect(component.totalSeats.length).toBe(100);

  // test some of the objects generated
  expect(component.totalSeats[0]).toEqual({ seatName: 'Seat-1', seatId: 'seat_1'});
  expect(component.totalSeats[99]).toEqual({ seatName: 'Seat-100', seatId: 'seat_100'});
});

如果基于事件/交互在组件中的某个位置调用了此函数,则可以设置一个间谍以检查是否成功调用了该函数。一个测试可能看起来像这样:

it('should test the initial seats generation', () => {
  // setup spy and check it hasn't been called yet
  const spy = spyOn(component, 'getInitialSeats').and.callThrough();
  expect(spy).not.toHaveBeenCalled();

  // do something that will invoke the function, here we just call it ourselves
  component.getInitialSeats();

  // check spy
  expect(spy).toHaveBeenCalledTimes(1);

  // test the amount of seats generated
  expect(component.totalSeats.length).toBe(100);

  // test some of the objects generated
  expect(component.totalSeats[0]).toEqual({ seatName: 'Seat-1', seatId: 'seat_1'});
  expect(component.totalSeats[99]).toEqual({ seatName: 'Seat-100', seatId: 'seat_100'});
});