A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function:

function retrieveNames() {
        var identifiers = [];
        var verifyAttribute = function (array, attr, value) {
            for (var i = 0; i < array.length; i++) {
                if (array[i][attr] === value) {
                    return false;
                }
            }
            return true;
        };
        for (var i = 0; i < result.length; i++) {
            var chosen = result[i];
            if (verifyAttribute($scope.names, "name", chosen.name) && identifiers.indexOf(chosen.id) === -1 && chosen.myInfo && chosen.name !== "") {
                $scope.fundNames.push({
                    name: chosen.name,
                    id: chosen.id
                });
                identifiers.push(chosen.id);
            }
        }
        ...
    }

I am seeking guidance on how to write a test that ensures I am correctly using the verifyAttribute function to eliminate duplicates based on both name and id. Despite attempting to use spyOn, I encountered errors.

I aim for a test scenario structured like this:

it('should validate the name and id to avoid duplicates', function() {
   //implement your solution here
});

Answer â„–1

It's not feasible to ridicule that approach without altering your current code base.

In my opinion, it would be ill-advised to try spying on a private function in your testing process. Ideally, your tests should focus on the external behavior of your functions and not their internal workings. This way, if you make changes to the internal structure, your tests won't need to change as well. In this scenario, it would be best to test the function getNames like a black box by setting $scope.names and then verifying the results from $scope.fundNames after calling it.

Alternatively, you could consider moving the checkAttr function outside of its current scope and spy on it to achieve the desired test case.

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

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...

How to store angular 2 table information generated using ngFor

I am currently working on a project where I need to create an editable table using data retrieved from the back end. My goal now is to save any updated data. I attempted to use formControl, but it seems to only save the data in the last column. Below is a ...

Trigger a jQuery event when a particular element has finished loading

Is there a way to globally detect when any element (such as textarea) is displayed on the page in order to perform a specific action? The element could also be added dynamically through an AJAX request. // This code snippet is just an illustration of the ...

When using nativescript-vue to navigate to a Vue page, the props are cached for later

A couple of days back, I managed to resolve the issue I was facing with navigating through Vue pages. However, after fixing that problem, I made an error by mistakenly attempting to pass an incorrect key value to the Vue page I was redirecting to. When th ...

The leaking of angular-material CSS onto other divs is causing unexpected styling

I am having trouble incorporating Angular Material's md-autocomplete into my angular application. I have already customized the CSS being used in my application, but when I add the Angular Material CSS, it messes up the entire page. Even when I tried ...

What is the best way to conceal text while retaining icons on a compact screen?

How can I hide the text links for Home, Reservations, My Reservations, About, and Settings on smaller screens while still keeping the icons visible? Currently, I am using the following resources: http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.1 ...

Having trouble importing components within my router.js file in VueJS

Trying to work with the vue-router, but encountering difficulty importing components into the router.js. Received a warning: [Vue Router warn]: No match found for location with path "/" In need of assistance as I'm unsure of what mistake I ...

Developing versatile form elements with Formik and the Yup library for React and Vite

I'm currently working on a React and Vite project where I'm trying to implement reusable form components using Formik and Yup, but I haven't been able to achieve it yet. I've created a component called <AppInputField/>, which is e ...

the function fails to run upon clicking the button again

Here is the current function in use: function beTruthful() { if (document.getElementById("about").style.opacity = "0") { document.getElementById("about").style.opacity = "1"; } else { document.getElementById("about").style.opacity ...

Differences in Print Layout Between Chrome and Firefox when Viewing a PHP Website

I have been working on creating a print command to print a specific div, and I have managed to successfully run the print command using default methods like CTRL + P and also with a button click. The Issue: However, I have encountered a problem where the ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind: function fetchDesign (items) { items.map(item => item.classList.add('selected')) // additional code here } Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensu ...

Creating a stunning image carousel in Vue by integrating a photo API: step-by-step guide

Trying to figure out how to create an image carousel in Vue using photos from an API. Currently able to display the photos using: <section class="images"> <img v-for="image in images" :key="image.id":src="image.assets.large.url"> &l ...

Dynamically adjusting the width of an HTML element with ng-style using percentage values in AngularJS

I am facing a challenge where I need to display a progress bar in my UI based on a percentage value stored in a JSON response object. Here is an example of the JSON object: { completionPercent: 42 } The desired UI outcome should look like this: ┌ ...

Fading colored images and backgrounds using Javascript

Although js and html are not my strong points, I am attempting to create two simple effects on a single page. As the user scrolls down the page, I want the background image or color to change as different divs come into view and then move off the screen. ...

When buttons contain an image instead of text, event.target.value will be undefined

I'm facing an issue with two buttons that are almost identical, except one includes an image while the other has text content. I have added onClick event handlers to both of them. Oddly, the event.target.value for the image button is coming up as und ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

Tips for maintaining the persistent state of tabs in a React.js application

I have created dynamic tabs using an array list, including nested tabs within those tabs. You can view the live sandbox link here: For the sandbox code and preview, visit: https://codesandbox.io/s/black-glade-phs69 The setup consists of 3 main tabs ...

Issues encountered while sending HTML Form data to MySQL with Node JS

I have been experimenting with a basic html form to mysql using nodejs, but unfortunately it is not functioning as expected. The HTML file is named index.html and the Node.js file is called test.js. Below you can find my code: My HTML <!DOCTYPE html&g ...

Is there a way I can turn off the dragging functionality in my situation?

Is there a method to disable the dragging functionality within a draggable element? $('#dragitem').draggable({ scroll : false, drag: function(event, ui){ //check if condition is met if(†...