Tips for obtaining Karma coverage for handling if-else scenarios in a controller method with Mocha/Jasmine testing suite

Below is the controller method in question:

function updateItem(itemList) {
            vm.selectedItem = '';
            if(itemList !== null || itemList !== '' && itemList !== undefined){
                if (itemList.firstName !== '' &&
                    itemList.firstName !== undefined &&
                    itemList.firstName !== null) {
                    vm.selectedItem += itemList.firstName + ' ';
                }
                if (itemList.lastName !== '' &&
                    itemList.lastName !== undefined &&
                    itemList.lastName !== null) {
                    vm.selectedItem += itemList.lastName + ' ';
                }
                if (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 - updateItem()', inject(function () {
            var itemList = [  
                {  
                    "id":111,
                    "firstName":"John",
                    "lastName":"Doe",
                    "type":"PERSONAL"
                 },
                {  
                    "id":222,
                    "firstName":"Jane",
                    "lastName":"Smith",
                    "type":"WORK"
                },
            ];
            var selectedItem = "John Doe PERSONAL-111"

            controller.updateItem(itemList);
            scope.$apply();
            expect(controller.selectedItem).to.equal(selectedItem);
            expect(controller.selectedId).to.equal(itemList[0].id);
        }));

When running tests, it is highlighted that the statements and branches are not fully covered apart from the functions themselves.

Thank you

Answer №1

To thoroughly test the itemList, consider using separate it() statements with slight variations each time. After making changes, rerun the changeItem() method and modify the itemList accordingly to meet the coverage requirements for each if statement. It is important to ensure that the test cases yield valuable information.

One suggestion is to declare the itemList in a beforeEach() function and then make slight adjustments to it in each it() test:

itemList[0].guestLastName = '';

Additionally, incorporating a 3rd party library like Ramda or Lodash for handling undefined/null checks can streamline your code. For instance, using if (!_.isNil(guestLastName)) { } can cover all 3 test scenarios effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Explore various date formats using the datepicker functionality

I'm dealing with the code below: <script type="text/javascript" language="javascript" src="~/Scripts/bootstrap-datepicker.min.js"></script> <script type="text/javascript" language="javascript" src="~/Scripts/locales/bootst ...

For each error that occurs when there is only one item in the array during a post request

My nodejs server has a JSON schema like this: var UserSchema = new Schema({ nick: String, deviceId: String, visivel: Boolean, checks: [{date: {type:String},log: {type:Number},lng: {type:Number}}] }); In the Post code ...

Why aren't my properties being reflected in the state after making changes?

Here is my Component Container code: import React, { Component } from 'react'; import { connect } from 'react-redux'; import Example from '../components/example.jsx'; class ExampleContainer extends Component { render() { ...

The AngularJS ng-if directive is failing to function properly, despite the logged boolean accurately reflecting the

I created a custom directive that handles the visibility of text elements on a webpage. While this logic works correctly half of the time, it fails the other half of the time. Here is the code snippet from my directive: newco.directive 'heroHeadline& ...

When making a POST request from the client-side JavaScript, the req.body is coming back as an empty

I have been encountering several questions related to the same topic, but unfortunately, none of them have resolved my issue. Hence, I am posting a new question here. My objective is to send a POST request from client-side javascript to the Backend using ...

Setting a port in Next.js: A step-by-step guide

I have one application currently running on port 3000 and I need to run another application on a different port in React Next.js. How can I make this change? In my package.json file, the current scripts section looks like this: "scripts": { & ...

webstorm error: unresolved function or method when using npm azure-storage modules

Encountering a problem with WebStorm IDE when using azure-storage library as it is unable to find the correct methods for intelligent coding (although the code runs without errors). View image of unresolved function or method Appreciate any help you can ...

In Node.js and Postgresql, encountering the error "Trying to access a property that is undefined" is common and can be frustrating

const pool = new pg.Pool(config); var tablename = req.body.tablename; pool.connect(function (err, client, done) { var query_get_value = 'SELECT * FROM '+ tablename; client.query(query_get_value, function (err, result) { d ...

ng-model fails to synchronize with HTML

When I click on ng-click, the model changes but the HTML remains the same... HTML <p>Reserved:<span>{{seatsInfo}}</span></p> <div ng-click="change()">change</div> JavaScript $scope.seatsInfo = 20; $scope.change = fu ...

Using AngularJS to recycle computed variables

In my template, I am in need of utilizing a calculated value to hide certain elements and perform other actions. <button ng-hide="expensive()" ng-click="foo()">foo</button> <button ng-show="expensive() && otherFunction()" ng-click=" ...

Is it possible for me to create a hyperlink that directs to a javascript function?

Here is the code I am currently using: <input class="button" type="button" value="Mark" onClick="doCheck('mark');" \> However, I would like to replace the button with a hyperlink using the <a> tag. Is it possible to achieve ...

What is the method for displaying map tooltips by default rather than on mouseover?

Currently, I have a script set up to display a map with two markers. Whenever I hover over one of the markers, a popup tooltip appears with location information. My question is, how can I make the information appear by default without needing to hover ov ...

Is there a way to verify the href attribute and potentially append the complete URL address if necessary?

Is there a way to verify the href attribute and replace it with a full URL if it doesn't contain the full path? I tried using JavaScript for this, but it doesn't seem to work on IE 8. This is my JavaScript code: fullUrl = $(this).filter('[ ...

Transforming a few lines of PHP header code to Classic ASP

I am encountering an issue with two files that I have: A locally hosted project coded in Ionic/AngularJS that is attempting to retrieve JSON data from an ASP file. An external ASP File which generates JSON data based on database values from a query. Eve ...

Is there a way in JavaScript to activate a web element by clicking on its center?

I have a webpage and I'm looking to simulate clicks using the console. I attempted to do so with the code snippet document.getElementById("myButtonId").click(), but it seems that the element only responds to clicks at its center location. Is there ano ...

Updating NavBar text dynamically based on user login status in React.JS

Within my project, there is a Navigation bar that I access from App.js. Depending on whether I am logged in or not, I want to display different versions of the NavBar. When logged in, the NavBar should have a logout button. And when logged out, it should s ...

Executing Java method via JavaScript by simply clicking a button

I am currently facing a challenge in finding a way to invoke a Java method from JavaScript and pass user input variables into the method call. The main issue I have encountered is that JavaScript seems to interpret/resolve the Java method during page load. ...

Interactive search functionality using jQuery

In the panel I have, I would like to include a search input field that allows users to type in a word. As soon as a match is found, that specific word will be highlighted within the panel while the other information disappears. ...

Experience the latest HTML5 features directly within a Java desktop GUI, with seamless communication through

This Java desktop GUI utilizes a Java-based web services communication layer along with an HTML library to provide powerful charting and interactivity. I am looking to integrate an HTML5 view within the Java GUI. Can someone assist me in managing JavaScri ...

How can I filter an array by a nested property using Angular?

I need help with objects that have the following format: id: 1, name: MyObj properties: { owners: [ { name:owner1, location: loc1 }, { name:owner2, location: loc1 } ] } Each object can have a different number of owners. I' ...