Issue
I am trying to write test case for the below method. I have written something like below but it does not improve /change code coverage. Can someone please help what I am doing wrong?
Component
remove(item: string, element:any){
const found = this.list1.find(el => el.team == element.tirname);
if(found){
var index = this.list1.indexOf(found);
if (index >= 0) {
this.list1[index].removeFlag = true;
const index1= this.list1[index].orgsUpdated.indexOf(item);
if (index1 >= 0) {
this.list1[index]['orgsUpdated'].splice(index1, 1);
this.list1[index]['removeFlag'] = false;
}
}
}
const found1 = this.list2.find(el => el.name == element.name);
if(found1){
var index2 = this.list2.indexOf(found1);
if (index2 >= 0) {
const index1= this.list2[index2].gOrgNames.indexOf(item);
if (index1 >= 0) {
this.list2[index]['gitOrganizationNames'].splice(index1, 1);
}
}
}
}
Spec file
it('should call remove', () => {
const spySubscribable = spyOn(component, 'remove');
let index = 0;
let item = "org1";
let element = [{
"team": 'team1',
"orgsUpdated": ["org1", "org2"],
"removeFlag":false
}];
component.remove(item,element);
component.list1[index] = element;
component.list1[index].removeFlag = true;
expect(component.list1[index].removeFlag).toBeTruthy;
expect(spySubscribable).toHaveBeenCalled();
expect(component.list1[0]).toEqual(element);
});
Solution
The issue is that spyOn(component, 'remove')
spies on the method to see how many times it was called and removes its implementation details. To keep its implementation details, add a .and.callThrough()
after the spyOn
.
Something like this:
it('should call remove', () => {
// change this line
const spySubscribable = spyOn(component, 'remove').and.callThrough();
let index = 0;
let item = "org1";
let element = [{
"team": 'team1',
"orgsUpdated": ["org1", "org2"],
"removeFlag":false
}];
// add this log and see what the value is and make sure
// this.list1.find returns something so it goes inside of the if
// block
console.log('List 1: ', component.list1);
component.remove(item,element);
component.list1[index] = element;
component.list1[index].removeFlag = true;
expect(component.list1[index].removeFlag).toBeTruthy;
expect(spySubscribable).toHaveBeenCalled();
expect(component.list1[0]).toEqual(element);
});
Answered By – AliF50
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0