Test the adjustment of the parameter value passed to a function within the Controller through unit testing

I need to verify if the passed variable is being modified within a function parameter. It's important that the variable itself undergoes a change.

For my unit tests, I am utilizing Karma and Jasmine.

In my Controller code snippet:

angular.module('myApp').controller('MyController', function($scope){
  $scope.functions = {};
  $scope.functions.deleteSomething = function(someObject, condition){
      someObject.someArray = someObject.someArray.filter(function(existingCondition){
          return existingCondition !== condition;
      });
  };
})

My Unit Test case:

describe('myControllerSpec', function(){
  var scope, controller;

  beforeEach(module('myApp'));
  beforeEach(inject(function($injector, $controller){
    scope = $injector.get('$rootScope').$new();
    controller = $controller('MyController', {
      $scope: scope
    });
  }));
  
  it("should validate if the provided variable gets altered or not", function(){
    object = {
        someArray: [
          {
            temp: 'dummy1'
          },
          {
            temp: 'dummy2'
          }
        ]
      };
    
    condition = {
      temp: 'dummy1'
    }
    scope.functions.deleteSomething(object, condition);
    expect(object.someArray).toEqual([
        {
          temp: 'dummy2'
        }
      ]);
  });
})

I'm facing challenges in understanding why the variable doesn't reflect any changes. Could this be due to its lack of attachment to scope?

However, I prefer not to link it to scope for testing purposes. Modifying the Controller isn't an option as someone else manages it.

Does anyone have any recommendations on how I can effectively test this piece of code?

Answer №1

When working in Javascript, the === operator is used to perform a reference equality check. An alternative approach is to utilize angular.equals():

  someObject.someArray = someObject.someArray.filter(function(existingItem){
      return !angular.equals(existingItem, newItem);
  });

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

Testing an asynchronous generator function in Jest using unit tests

I need help writing a unit test for a generator function where I am struggling to properly mock a read stream object (ReadStream). Here is the function I'm trying to test: public async *readChunks(file: string, chunkSize: number): AsyncIterableIter ...

Adjusting the size of a Video/Image Slider to perfectly fit the screen dimensions (both width and height

I have been using a slider code to display my images and videos. The code can be found here: Code:https://codepen.io/1wdtv/pen/jbjZeb The issue I am facing is that the slider is only responsive in terms of width. This means that when resizing the browser ...

Encountering the error "Uncaught reference error: $ is not defined" despite ensuring that scripts are loading in the correct order. However, the scripts work from the

Encountering an Issue: "Uncaught ReferenceError: $ is not defined" Whenever I try to utilize $('#someid') in my custom JavaScript code within an Electron app. All scripts are properly arranged in my HTML file: <script type="text/javascri ...

Issue encountered during unit testing: "Error occurred: 'Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1'"

I am encountering an issue while trying to perform unit testing on a service. The error that I am seeing when running the test is: Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at MapSubscriber.project (auth.service ...

Changing the size of an image while scrolling

I'm currently working on a website and I'm trying to implement a feature where the logo on the page changes size based on the user's scroll behavior. However, I'm facing difficulty in finding a universal formula that can adjust the logo ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...

React app experiencing issues with onClick button methods not functioning as expected

Here is the React code for a sample homepage. My intention was to have the function run and update the page when the buttons are clicked. However, instead of updating the page, it keeps showing alerts. I have confirmed that the fetch function is pulling da ...

Navigating through the various iterations of jQuery

Unique Case Study I'm currently facing a dilemma involving the integration of jstree and jquery-ui datepicker. The scenario is this: I am attempting to utilize jquery-ui-datepicker on an input element that is dynamically inserted into the DOM after ...

Please add color to the space beneath the line in a highchart

I have been tasked with customizing a line chart that was not originally created by me. The application pulls data from a database and organizes each element by hour before displaying it on the chart. When you hover over a point, the interface looks like t ...

Error Message: "Unexpected use of Hook in react-hook-form"

I am still getting acquainted with react hook form so I have encountered a minor issue. To my surprise, Controllers are unable to handle values as numbers. At first, this was frustrating, but after some searching, I stumbled upon this helpful github issue ...

useEffect initiates all actions

I'm currently exploring hooks functionality within a Next.JS project. I've successfully used a useEffect to track scrolling behavior in order to dynamically change the content displayed in a header when the page is scrolled. const [ scrollY, setS ...

Unraveling request parameters in Angular: A step-by-step guide

I am looking to create a unique URL structure like http://mydomain.com/token/abc12345, where abc12345 is a variable parameter that needs to be extracted. Upon detecting this URL in Angular, I want to extract the token, perform a database lookup, populate ...

Synchronize display with data loading

My plan involves executing 2 AJAX calls: Loading a partial HTML template. Fetching JSON data for the template and displaying it within the loaded template. The JSON must be retrieved separately from the template because users might initiate a "refresh" ...

Cut the text within each individual container

For many of you, the question I'm about to ask is quite simple. Take a look at the following HTML code: <div class="content" id="content"> <div class="container" id="container"> <h1>Title</h1> <img class ...

Is there a way to make the React component automatically refresh upon clicking the search button?

Just starting out with React and JavaScript, I decided to experiment with accessing a public API. Here is the function I created: import { useState } from "react"; import CountrySWR from "./CountrySWR"; export default function SearchFo ...

What could be causing my project to install an erroneous Angular version?

It appears that my project is not utilizing the latest Angular code, but I am unsure of the reason behind this. I have checked my package.json file and found the following dependencies: "devDependencies": { "@angular/common": "2.0.0", "@angular ...

Is there a way to dispatch an event from one Angular ui-router view to another view?

In order to change the login button to display "logged in as xxx" after authentication, I have structured my page into three views: header, content, footer. The login button is located in the header view. Upon clicking login, it transitions to the "app.log ...

Clicking on the mail icon will open the mail with the associated mail id

https://i.sstatic.net/6TLpN.pngWhen the mail icon is clicked, the mail will open with this email address. I am currently working on a project where clicking the mail icon will redirect to the mail signup page with the corresponding email address. In the ...

ways to display a chosen option in a dropdown menu

Below is the code snippet I am currently using, which involves JQuery and Bootstrap 4: $('.dropdown-menu li').on('click', function() { var selectedValue = $(this).text(); $('.dropdown-select').text(selectedValue); }); & ...

Ways to implement a fixed navigation bar beneath the primary navbar using ReactJS

Utilizing ReactJS, I am endeavoring to create a secondary (smaller) navbar in the same style as Airtable's product page. My primary navbar is situated at the top and transitions from transparent to dark when scrolled. The secondary bar (highlighted in ...