Evaluating an array of dependencies in Angular controller tests

Currently, I am in the process of learning AngularJS while working on a small Real estate app. Since I am fairly new to AngularJS, controller testing with multiple dependencies is proving to be quite challenging for me. Despite searching online for information, I have found very limited resources on this topic. Any guidance or assistance would be greatly appreciated.

One specific test that is currently failing is as follows:

it('should create "properties" model with 1 property fetched from xhr', function() {
  $httpBackend.flush();
  scope.properties = scope.getResultsPage(1);

  expect(scope.properties).toEqual(propertiesData());
});

ControllersSpecs.js:

'use strict';

/* Controller specifications go here */
describe('Realty controllers', function() {

  beforeEach(module('realtyApp'));
  beforeEach(module('angularUtils.directives.dirPagination'));
  beforeEach(module('realtyFilters'));
  beforeEach(module('realtyServices'));


  describe('PropertyListCtrl', function(){
    var scope, ctrl, $httpBackend;

    function propertiesData() {
      return {
        "total": 1,
        "data":[{
          "id": "26",
          "property_type": "apartment",
          "amount": "600",
          "address": "26 Marsh St, Wolli Creek",
        }]
      }
    };

    // For more information on dependency injection for testing purposes
    // https://docs.angularjs.org/tutorial/step_05
    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {

      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET('/api/properties?page=1').
          respond(propertiesData());

      scope = $rootScope.$new();
      ctrl = $controller('PropertyListCtrl', {$scope: scope});
    }));


    it('should create "proterties" model with 1 property fetched from xhr', function() {
      $httpBackend.flush();
      scope.properties = scope.getResultsPage(1);


      // scope.properties = propertiesData();
      expect(scope.properties).toEqual(propertiesData());
    });
  });
});

Main app module:

'use strict';

/* App Module */

var realtyApp = angular.module('realtyApp', [
  'ngRoute',
  'angularUtils.directives.dirPagination',
  'realtyControllers',
  'realtyFilters',
  'realtyServices'
]);

Property List controller

'use strict';

/* Controllers */

var realtyControllers = angular.module('realtyControllers', []);

realtyControllers.controller('PropertyListCtrl', ['$scope', 'Property', 'propertyImage', 'propertyData',
  function($scope, Property, propertyImage, propertyData) {
    $scope.beds = propertyData.beds();
    $scope.bathrooms = propertyData.bathrooms();
    $scope.garageSpaces = propertyData.garageSpaces();

    // Pagination settings
    $scope.totalProperties = 0;
    $scope.propertiesPerPage = 10; 

    $scope.pagination = {
        current: 1
    };

    // Retrieve results page
    $scope.getResultsPage = function getResultsPage(pageNumber) {
      
      Property.get({page:pageNumber}, function(result) {
        $scope.properties = result.data;
        $scope.totalProperties = result.total;
      });
    }

    $scope.getResultsPage(1);

    $scope.pageChanged = function(newPage) {
        $scope.getResultsPage(newPage);
    };

    // Check if car space is available
    $scope.isCarSpaceAvailable = function(carSpace) {
      if (carSpace != 0) {
        return true;
      }
      return false;
    }

    // Get property image based on photo name
    $scope.getPropertyImage = function(photo) {
      return propertyImage.jpg(photo.name);
    }

    // Clear filters
    $scope.clearFilters = function() {
      $scope.filter = {};
    }        
  }]);

Edit 1:

An error that I am encountering is:

Answer №1

When you set scope.properties = scope.getResultsPage(1);

You are assigning the result of getResultsPage to properties, but since nothing is returned from that function, properties will not be affected.

Have you tried adding a flush call after the method? Here is an example:

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

  $httpBackend = _$httpBackend_;
  $httpBackend.whenGET('/api/properties?page=1')
      .respond(propertiesData());
    /**** your code *****/
}));


it('should create "properties" model with 1 property fetched from xhr', function() {

  $httpBackend.expectGET('/api/properties?page=1');
  scope.getResultsPage(1);
  $httpBackend.flush();


  // scope.properties = propertiesData();
  expect(scope.properties).toEqual(propertiesData());
});

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

Options for managing URLs with jQuery

I've been working with a jQuery user interface component called aciTree, which is a tree list that uses Ajax as the data source. When I provide a URL that returns JSON, everything functions properly. However, I need to generate the JSON dynamically an ...

Hover over a ListItem

Looking for advice on how to incorporate a Mouseover feature into a Material UI ListItem from the following link: http://www.material-ui.com/#/components/list. As the "SecondaryText" is limited to 2 lines, I am exploring options to display additional data ...

Tips for eliminating the trailing slash from the end of a website article's URL

I've recently delved into learning Gatsby, and I've encountered an issue with the Open Graph tag in my project. The og:image is displaying a different image than the intended thumbnail for the article. Here's an example article - . When try ...

Checking an HTML form for accuracy upon submission using JavaScript

I've been researching how to accomplish this task, and I have successfully implemented the validation process. However, I'm encountering difficulties with the actual form submission. Currently, the text fields are being validated properly and er ...

Creating an AngularJS directive with the help of the angular.module function

Could someone please help me understand why I am getting an "Argument 'MainCtrl' is not a function, got undefined" error? It seems to be related to module dependency injection when using directives. angular.module('app', []) .control ...

"Utilizing AngularJS $resource with a custom GET action consistently invokes the default getAll method within a Spring REST controller

Currently, I am in the process of developing a web application using AngularJS and Spring REST. I have utilized JPA's single table inheritance for reference data such as Gender, Languages, and UserTypes, with ReferenceData as the base class and Langua ...

An error has occurred: "Alert: Index is not defined" when using PHP in conjunction with Ajax

Below is the Javascript code snippet I am using: $( ".modifica_sore" ).click(function(){ var button = this; $.ajax({ type: "POST", url: "action/modifica_professori.php", data: { nome: $(button).siblings('[name="nome" ...

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

How can controllers be utilized within Directives in AngularJS?

I am currently exploring Angular and trying to understand the various ways to work with its elements. While researching on blogs, such as this article on Learning Directives in Angular, I discovered that a controller can be used to initialize scope. Howeve ...

Troubleshooting a Messaging Error between Background and Another Script

Attempting to transfer selected text from the current page to an HTML page using message passing: content script to background script, then background script to the HTML page. However, encountering errors if the HTML page is not already open, and even gett ...

What is the best way to attach 'this' to an object using an arrow function?

Consider having an object named profile which consists of properties name and a method called getName (implemented as an arrow function). profile = { name: 'abcd', getName: () => { console.log(this.name); } } I am interes ...

Issues with uploading files in AngularJS

Using Java Controller class: @RequestMapping(value = "/sendFile" , method = RequestMethod.POST , consumes="multipart/form-data") public void sendFile(@RequestParam MultipartFile file) { System.out.println("*****"+ file); } Within the html file: ...

The Bootstrap navigation menu is functioning properly when opening, but has an issue when attempting

Creating a mirrored version of an HTML file using NuxtJS, I've included the following code snippet in the Navbar component for my NuxtJS project. <template> <section id="navigation-menu" class="menu menu3 cid-sLhoPz7Ycg" ...

Guide on attaching an onclick event to a button created with a string in Next.js?

<div onClick={(event) => this.addToCart(event)}> <ReactMarkdownWithHtml children={this.props.customButton} allowDangerousHtml /> </div> In my current situation, I am facing an issue with the code above. The button is being rendered ...

utilizing Angular's jqlite for targeting elements of identical type

Currently, I am working on some HTML5 Video to Canvas manipulations. In my code, I have created a directive where I need to select specific child elements. This has been easy so far, but I encountered an issue when dealing with 2 canvas tags. Below is the ...

Emphasize a portion of a text / Apply formatting to a variable

I am facing an issue where I need to format only the date in a specific string. I have managed to extract the date and store it in a variable after isolating it from the original message. <div class="foo"><p> Click here now and get by January ...

Experimenting with Extjs compatibility using Selenium

I am currently in the process of testing an extjs application using Selenium. I am utilizing Selenium IDE for Firefox and Javascript with Eclipse on Chrome. Despite spending countless hours searching for a solution to my problem, I have been unable to iden ...

Change the text field's border color if the field is not empty

On my website, there is a TextField where users can enter values to perform a site search. My question pertains to the border color of this field. Normally, the border color is black when the field is not in use. However, when a user clicks on the field an ...

[Error: hex is not recognized as a valid function]

Snippet of my Code: jwt.verify(token,JWT_SECRET,(err,payload)=>{ if(err){ res.status(401).json({error:"You must be logged in"}) } const _id = payload._id collection_name.findById(_id) .then(userdata=>{ req.user = p ...

What could be the reason for the undefined value of my variable

I am facing an issue with a function that I have written function collectData() { var data = []; data[0] = {name: "Sophia", age: 25, gender: "female"}; data[1] = {name: "John", age:30, gender ...