Could you provide some guidance on how to properly test this AngularJS code using Jasmine?

Here is a simple function I have:

wpApp = angular.module('wpApp', ['ngRoute']);

wpApp.controller("ctrlr", function($scope) {
    $scope.message = 'This is the page';
});

I am attempting to test it using Jasmine with this spec:

describe("Testing suite", function() {
    var scope;
    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        $controller("controller", {
            $scope: scope
        });
    }));

    it("should display the default message", function() {
        return expect(scope.message).toBe('This is the page');
    });
});

Unfortunately, it is not functioning as expected, as the actual value is returning as Undefined.

Since I am new to AngularJS and the concept of injection, I have been researching on StackOverflow, the documentation, and various tutorials, but I am still unable to pinpoint the exact issue.

Hopefully, the solution is a simple one. Can someone offer guidance on what adjustments I need to make to my spec?

Answer №1

To properly set up your module:

beforeEach(loadModule('wpApp'));

Next, make sure to load the correct controller:

$controller("ctrlr", {
    $scope: scope
});

Full code snippet:

describe("Testing suite", function() {
  var scope;

  beforeEach(loadModule('wpApp'));

  beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    $controller("ctrlr", {
      $scope: scope
    });
  }));

  it("should display the default message", function() {
    return expect(scope.message).toBe('This is the page');
  });
});

Alternatively:

describe("Testing suite", function() {

  var $scope;

  beforeEach(function() {

    loadModule('wpApp');

    inject(function($rootScope, $controller) {

      $scope = $rootScope.$new();

      $controller("ctrlr", {
        $scope: $scope
      });
    })
  });

  it("should display the default message", function() {
    return expect($scope.message).toBe('This is the page');
  });
});

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

Persist the scroll position within a div even after refreshing a PHP file using AJAX

I have a specific div set up with its own scroll bar, which is being refreshed using AJAX (with a PHP file). Whenever I scroll within this div and trigger a reload, the inner scrollbar resets back to the top. My goal is to retain the position of the scroll ...

React state update not triggering a component re-render

I've been attempting to toggle the visibility of a div by clicking on another div, but I'm encountering an issue. The div becomes invisible on the first click only if it was visible initially. After that, it remains invisible and does not update. ...

Is it possible to prompt npm to install a sub-dependency from a GitHub pull request?

Currently, I'm in the process of setting up geofirestore, which has a dependency on geofirestore-core. However, there is an existing bug in geofirestore-core that has been addressed in a pull request. How can I make sure that my geofirestore installa ...

Instructions on how to use a keyboard key to activate a dropdown menu item in Bootstrap

Bootstrap 5 navbar features dropdown menus that have underlined hotkeys such as a,n,s, and e. https://i.sstatic.net/bZOaC1kU.png <div class="btn-group"> <button type="button" class="btn btn-danger dropdown-toggle" ...

Backstretch malfunctioning

Looking to enhance my webpage with a backstretch image slideshow effect using the body background, but encountering issues. The code I have included before the </head> tag is: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery ...

Ways to substitute PHP functions using AJAX

I'm a beginner with AJAX. How do I replace the initial PHP function after an AJAX action is executed? It seems that the page does not refresh after the action takes place. Below is the code: Javascript function set_ddm(another_data) { var resul ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

IE and Firefox display different responses when encountering an empty XML document

When working with jQuery to read an XML file, I occasionally encounter the situation where the XML is empty. In this case, I anticipate that the error function (no_info) will be triggered because the file is not formatted as expected for the dataType. Int ...

Vue: Changing the value in the select dropdown causes input fields to reset their content

After setting up a form with input values, I noticed that when using a select element with a v-model to change the dropdown value, the input fields from the previous selections are cleared. This has been a persistent issue for me and is now starting to imp ...

The AngularJS ng-class expression checks for a substring that matches the current day's date

In the code snippet below, I have a table populated with rows using ng-repeat and a JSON data source. <tbody> <tr ng-repeat="roll in filtering(JSON) | orderBy:[sortType,'Cutoff']:sortReverse | filter:q as results" ng-class="{ ' ...

Mobile viewing causing problems with website buttons functionality

While my website functions perfectly on desktop, I am facing an issue where the buttons are not working when accessed through mobile devices. Interestingly, these buttons were operating fine in a previous version of the site. Although I have made minimal ...

Utilizing useEffect to retrieve and display an empty array in a React component

I am currently developing a React application that leverages Fetch to retrieve data from an API using SQLite. Strangely, when I check the console, it only displays a length of 3 and Array[0]. This means I can't access data based on specific IDs like I ...

Deciphering the Components of Web Applications: Express.js, Angular.js, and the MVC Puzzle

After exploring numerous discussions on Stack Overflow regarding the integration of Express.js with Angular.js and the presence of dual MVC components in both the client and server sides of web applications, I have found myself feeling somewhat perplexed. ...

What's causing me to encounter two canvases while implementing PIXI.js in my Next.js project?

I'm facing a challenge in my game development project that utilizes PIXI.js within a Next.js setup. Currently, I am experiencing an issue where the webpage is displaying two canvases instead of one, leading to unexpected rendering issues and impacting ...

What is the best way to save a PDF from within a frame using JavaScript and an HTML5 <embed> tag?

I'm looking for assistance with a script for my website that dynamically generates a PDF after the user makes selections in one of the frames. The website uses the HTML5 tag to display the PDF file. Can anyone provide guidance on a script that can: ...

Encountering a blank or 404 error page in React after running npm build - let's troubleshoot where the issue might be

Upon running npm build(react), my index.html displays a blank page. To address this issue, I initially attempted the following steps: Adding the following line in package.json homepage : "./" or "." or "absolute file PATH" ...

unnecessary files in the node_modules directory in Rails

I am a beginner in Node.js and unfamiliar with npm and modular JavaScript. After using the browserify-rails gem, I noticed that there are multiple files from a GitHub repo stored in the node_modules folder after running npm install. Since I only require ...

What is the reason behind the blocking of Ajax GET requests without CORS, while JSONP requests are permitted?

Accessing any page on the web through a GET request using HTML tags from a different origin is possible: <script src="http://example.com/user/post?txt=sample"></script> XHR requests to other origins are blocked for security reasons. For examp ...

Executing MySQL queries through JavaScript functions

I need to create a PHP function that I can use in my JavaScript code. The issue I'm facing is that the variables from the beginning of the file are not recognized in the JavaScript block. <!DOCTYPE html> <?php include 'pdo_connect.php&a ...

Locate a specific text within a complex array of objects and retrieve the objects that contain the match as

I have an array of objects named input as shown below. Each object in the array contains a property vertical of type string, an array called platformList, and a nested object named radar_metadata. I am looking to implement a search functionality where I c ...