Reputation: 33
I have this below method in one of my components. How can I write a unit test for it?
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;
}
}
Upvotes: 0
Views: 2166
Reputation: 6193
Before writing the unit test, I would suggest that you improve your function a bit. There is some code in there that you don't necessarily need. Have a look at this improved function that does the exact same thing.
getInitialSeats() {
for (let i = 1; i <= 100; i++) {
this.totalSeats.push({
seatName: "Seat- " + i,
seatId: "seat_" + i
});
}
}
To test this function I would just write a very simple test case like this (I assume this function is in a component):
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'});
});
If this function is called somewhere in your component based on an event/interaction then you could set up a spy to check whether it was sucessfully called. A test could look like this:
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'});
});
Upvotes: 1