Reputation: 27
I am trying to improve code coverage of Angular app. In code coverage it is mentioned that if else condition is not covered. Could anyone tell me how to do that? Feel free to ask for more code details.
public searchByText(textVal: any): void {
let matchedEquipments = [];
// **
if (this.model.searchText.length > 1) {
matchedEquipments = this.refineByText(textVal, this.equipments);
} else {
matchedEquipments = this.equipments;
}
// **
matchedEquipments = this.refineByPlant(this.model.plants, matchedEquipments);
matchedEquipments = this.refineByPlantIsland(this.model.plantIslands, matchedEquipments);
matchedEquipments = this.refineByProcess(this.model.processes, matchedEquipments);
matchedEquipments = this.refineByIndustry(this.model.divisions, matchedEquipments);
this.displayClientData(matchedEquipments);
this.updateSearchCounters(SelectionFilter.FreeText);
}
Spec:
it('verify the result with search', async(() => {
equipmentSelectionComponent.searchByText("123");
//equipmentSelectionComponent.model.searchText = "123";
expect(equipmentSelectionComponent.matchedData.length).toBeGreaterThan(0);
}));
Upvotes: 1
Views: 322
Reputation: 17514
You need write more than just 1 it
block to test this:
it('should call "refineByText" when search Text is there', async(() => {
spyOn(equipmentSelectionComponent,'refineByText').and.callThrough();
equipmentSelectionComponent.model.searchText = "some Val";
equipmentSelectionComponent.equipments = ["item1"]
equipmentSelectionComponent.searchByText("123");
expect(equipmentSelectionComponent.refineByText).toHaveBeenCalledWith("123",["item1"]); // <-- this will check true condition
// I dont see "matchedData" in your provided code so I dont know about this check.
expect(equipmentSelectionComponent.matchedData.length).toBeGreaterThan(0);
// spy and check other function calls as well just like I did for refineByText
}));
it('should not call "refineByText" when search Text is empty', async(() => {
spyOn(equipmentSelectionComponent,'refineByText').and.callThrough();
equipmentSelectionComponent.model.searchText = "";
equipmentSelectionComponent.searchByText("123");
expect(equipmentSelectionComponent.refineByText).not.toHaveBeenCalled(); // <-- this will check true condition
// similarly use use "toHaveBeenCalledWith(val) for other functions
}));
I wouold recommend you to read testing with spies and also some more basic testing ways of angular. This would help you to get more familiar with unit testing mindset. Feel free to clap as well !! :)
Upvotes: 1
Reputation: 437
Below test cases should be able to include the coverage for your test case
if condition : should assign to matchedEquipments by modifying the equipments when searchText has value
Expectation :
refineByText toHaveBeenCalledWith(textVal, this.equipments)
else condition : should assign equipment to matchedEquipments when searchText has no value
Expectation :
refineByText not.toHaveBeenCalledWith(textVal, this.equipments)
Upvotes: 0