如何使用Angular 6/Jasmine对这个简单函数进行单元测试
我在我的一个组件中有以下方法。如何为它编写单元测试如何使用Angular 6/Jasmine对这个简单函数进行单元测试,jasmine,angular6,karma-jasmine,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.sea
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;
}
}
getInitialSeats(){
for(设i=0;i<100;i++){
i=i+1;
此.seatObj={
座位名称:“座位-”+i,
seatId:“座位”+i
}
this.totalSeats.push(this.seatObj);
this.seatObj={};
i=i-1;
}
}
在编写单元测试之前,我建议您稍微改进一下功能。其中有一些代码是您不一定需要的。看一看这个改进的函数,它做了完全相同的事情
getInitialSeats() {
for (let i = 1; i <= 100; i++) {
this.totalSeats.push({
seatName: "Seat- " + i,
seatId: "seat_" + i
});
}
}
如果此函数是基于事件/交互在组件中的某个位置调用的,那么您可以设置一个间谍来检查是否成功调用了它。测试可以如下所示:
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'});
});
他要求一个简单的函数。。。你在哪里看到“组件”?!例如,如果它是一个验证器?!
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'});
});