What methods can I use to evaluate my Angular scope functions in karma and jasmine?

I recently started learning Angular and am new to Jasmine testing. I have a function in my controller that adds an object from JSON data into an empty array.

My controller with the cart-related functions:

$scope.cart = [];

  $scope.addItemToCart = function(choc) {
    var cartItem = readCartItem(choc.id);
    if(cartItem == null) {
      //if item doesn't exist, add to cart array
      $scope.cart.push({type: choc.type, id: choc.id, price: choc.price, quantity: 1})
    } else {
      //increase quantity
      cartItem.quantity++;
    }
  }

  $scope.cartTotal = function() {
    var sum = 0;
    $scope.cart.forEach(function(item) {
      sum += item.price * item.quantity;
    });
    return sum;
  }

  $scope.getTotalQuantity = function() {
    var totalItems = 0;
    $scope.cart.forEach(function(item) {
      totalItems += item.quantity;
    });
    return totalItems;
  }

  $scope.clearCart = function() {
    $scope.cart.length = 0;
  }

  $scope.removeItem = function(choc) {
    $scope.cart.splice(choc,1);
  }

  function readCartItem(id) {
    //iterate thru cart and read ID
    for(var i=0; i<$scope.cart.length; i++) {
      if($scope.cart[i].id === id) {
        return $scope.cart[i]
      }
    }
    return null;
  }

Test Scenario:

  describe('Controller: ChocoListCtrl', function () {

  beforeEach(module('App'));

  var scope, ctrl;

  beforeEach(inject(function ($controller, $rootScope) {


    scope = $rootScope.$new();
    ctrl = $controller("ChocoListCtrl", { $scope:scope })
  }));

  it('should be defined', function (){
    expect(ctrl).toBeDefined();
  });

  it('should have an empty cart', function(){
    expect(scope.cart.length).toBeLessThan(1);
  });

  describe('cart functions', function(){
    beforeEach(function(){
      scope.addItemToCart();
    })

    it('should add objects into the cart', function(){
      expect(scope.cart.length).toBeGreaterThan(0);
    })
  });

When running the test, I encountered the following error:

TypeError: undefined is not an object (evaluating 'choc.id')

Despite pushing an object into the array, are there any missing elements or should I consider including the JSON file for assistance?

Any advice or guidance would be greatly appreciated. Thank you!

Answer №1

By failing to provide a parameter for $scope.addItemToCart, the function is unable to read the value of choc and returns undefined.

The source of the issue lies in this particular line of code:

beforeEach(function(){
  scope.addItemToCart(); // Missing parameter input
})

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

Perform the function prior to making any adjustments to the viewmodel attributes

Within my view, I am showcasing employee details with a checkbox labeled Receive Daily Email. When a user interacts with this checkbox, I want to trigger an AJAX function to validate whether the user is allowed to modify this setting: If the result is tru ...

Guide on exporting a function from a module as a class property

How to export a function as a class property from a module? Even if modifiers such as public are added, when a class property points to a function within a module, it behaves as though it is private. There are multiple ways to define a property (a, b, c ...

What additional requirements are needed for Rails and remote AJAX with the "true" setting?

I'm a bit confused about the purpose of remote:true in Rails forms. I initially thought that it required some Javascript to enable asynchronous functionality, but instead it seems to be causing issues with my page. Below is a simple index.html.haml f ...

Crawlers designed to handle websites with never-ending scroll feature

Currently seeking a crawler application that can analyze the JavaScript on a webpage for AJAX requests and identify functions that initiate those calls in order to retrieve all content from start to finish. I would develop this myself, but my workload is ...

The JsonConverter and EntityData are essential components for processing and

My Azure web service is set up with a database-first EF approach. One of the entities that I have defined in Azure is as follows: public class Company : EntityData { public string CompanyName { get; set; } } This entity inherits the Id property from ...

Type in "Date" and select a date using your mobile device

Hey, does anyone know a good solution for adding placeholder text to an input with type="date"? I'm looking for a way to utilize the phone's built-in date selection feature on a website, rather than having users manually enter dates using the ke ...

Datatables ajax response not loading data into table

I don't have much experience with JavaScript, so I believe there may be a misconfiguration or something that I'm overlooking. My current setup involves using Datatables v1.10.7. I have a table with the required parts - a thead, tfoot, and a tbod ...

Display the input field value using ReactJs

Is there a way to immediately show the value of my input in the render function? While exploring the state and lifecycle concept in a React component, I came across the usage of a constructor with super(props) and this.state. However, when I attempted to ...

When utilizing the Express framework, the object req.body is initially empty when collecting data from a basic

I'm encountering an issue where I receive an empty object in req.body when submitting my HTML form. This problem persists whether testing in Postman or directly submitting the form from localhost in the browser. Upon logging it in the node console, t ...

The JQUERY Click event fails to trigger only on the initial click

While attempting to display the name stored as a data value for each button in the code, I encountered an issue where it wouldn't work on the first click event call. However, after the initial click, it operated normally. It is important to note that ...

Unable to retrieve Objects from JSON

Here is a JSON object I received: [{"model": "pricing.cashflow", "pk": 1, "fields": {"value": 4.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 2, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 3, "fiel ...

Does an equivalent of the JQuery PHP Library exist, utilizing $.ajax in place of $.php?

The JQuery PHP Library introduces an object named $.php, which operates similarly to $.ajax. Here is an example of how it can be used: $.php(url); php.complete = function (){ $('#loading').slideUp('slow'); } While this library enh ...

Upgrade the jQuery code from version 1.4.2 min to version 1.10.2 min

Hey there, I'm looking for assistance with updating the code below to use jQuery 1.10.2. The backslashes are present because I am using it with PHP and need to escape special characters. I'm not very familiar with JavaScript and unsure of the ch ...

Simple method for swapping out an HTML string with image tags solely using JavaScript

In our Ionic 2 App, we are displaying content from a backend API in the form of Questions and Answers. The Answers are generated using summernote, allowing us to render raw HTML in the app. However, we need to replace all instances of img tags in the answe ...

Retrieve information from a JSON file and utilize it across three different fragments

I am using Volley to retrieve data from JSON. Within my Activity, I have three Fragments that need to be populated with this JSON data. I want to fetch the data from JSON only once and then use it in all three Fragments. I store the received data in a List ...

What are some ways to prevent "window.onbeforeunload" from appearing when a form is submitted?

Is there a way to prevent the alert box from appearing when submitting a form using the Submit button below? I want to avoid being prompted to "Leave this page" or "stay on this" after submitting the form. <script> window.onbeforeunload = ...

Steps to avoid IE11 prompt (Do you really want to leave this site)

In the midst of making a webpage, I find myself faced with the peculiar issue of only having a dropdown to select. To make matters worse, when attempting to navigate to the next page in IE11, a pesky message pops up. Curious about the default behavior of ...

Having trouble executing a Hive query involving JSON data?

My data includes the following: {"field1":{"data1": 1},"field2":100,"field3":"more data1","field4":123.001} {"field1":{"data2": 1},"field2":200,"field3":"more data2","field4":123.002} {"field1":{"data3": 1},"field2":300,"field3":"more data3","field4":123. ...

The ID data from my axios.delete request is not properly transferring to the req.body, causing issues with deleting from mySQL

Currently, I am utilizing Axios to manage the requests in my application. Upon testing with PostMan, it has been confirmed that my DELETE request is functioning properly. However, when implementing the code for the front end, I encountered a 404 error duri ...

Loading jQuery on Ajax can be a challenge

I am currently faced with the challenge of working on code that I did not write myself or fully comprehend. The page utilizes AJAX to dynamically load content, and my goal is to manipulate this content. However, when I try to apply jQuery to the dynamic el ...