简体   繁体   中英

How to get Karma coverage for the if else cases in controller method using Mocha / Jasmine?

I have the below controller method:

 function changeItem(itemList) { vm.selectedItem = ''; if(itemList !== null || itemList !== '' && itemList !== undefined){ if (itemList.guestFirstName !== '' && itemList.guestFirstName !== undefined && itemList.guestFirstName !== null) { vm.selectedItem += itemList.guestFirstName + ' '; } if (itemList.guestLastName !== '' && itemList.guestLastName !== undefined && itemList.guestLastName !== null) { vm.selectedItem += itemList.guestLastName + ' '; } Iif (itemList.type !== '' && itemList.type !== undefined && itemList.type !== null) { vm.selectedItem += itemList.type + '-'; } if (itemList.id !== '' && itemList.id !== undefined && itemList.id !== null) { vm.selectedItem += itemList.id + ' '; if (itemList.id === "All") { vm.selectedId.push(vm.itemLists.id); } else { vm.selectedId = itemList.id; } } } } } 

spec.js:

 t('listController - changeItem()', inject(function () { var itemList = [ { "id":111, "guestfirstName":"Test", "guestlastName":"Test", "type":"BUSINESS" }, { "id":222, "guestfirstName":"Test", "guestlastName":"Test", "type":"BUSINESS" }, ]; var selectedItem = "Test Test BUSINESS-111" controller.changeItem(itemList); scope.$apply(); expect(controller.selectedItem).to.equal(selectedItem); expect(controller.selectedId).to.equal(itemList[0].id); })); 

But, when i run test, it says the statements and the branch is not covered except the functions.

Thanks

You can have separate it() statements to check various pieces of the itemList, changing it subtly each time, then rerunning the changeItem() method. Then you would tailor that itemList to reach into each if statement to reach the coverage you require. Bear in mind that you have to be sure that the test provides something.

I'd probably move the itemList declaration out to a beforeEach() then in each it() test, alter it slightly:

itemList[0].guestLastName = '';

On another note, I'd suggest getting a 3rd party library such as Ramda or Lodash to handle your undefined/null checks. if (!_.isNil(guestLastName)) { } for example would cover all 3 of your tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM