Exploring the functionality of Angular's Controller As using Jasmine testing framework

I am a beginner in Jasmine/Angular testing and I'm attempting to test a controller that I have created. The code for the controller is shown below:

(function () {
'use strict';

angular
    .module('App')
    .controller('ActionEventsCtrl', ActionEventsCtrl);

ActionEventsCtrl.$inject = ['$log', 'ActionEvents'];

function ActionEventsCtrl($log, ActionEvents) {
    /* jshint validthis:true */
    var vm = this;
   
    vm.ActionEvents = [
                { "description": "Second Notification", "type": 4, "dateRaised": "2014-10-17T00:00:00", "hasNotified": true, "status": 0, "user": null, "id": 6 },
                { "description": "Third Notification", "type": 2, "dateRaised": "2014-10-18T00:00:00", "hasNotified": true, "status": 1, "user": null, "id": 7 }
    ];

    vm.init = getActionEvents();

    function getActionEvents() {
        var userId = 1;
        ActionEvents.get(userId).then(
            function onSuccess(response) {
                vm.ActionEvents = response.data;
        },
        function onFailure(response) {

            $log.error("Loading of ActionEvents failed with response: ", response);
        });

    }
}

})();

In order to test this controller, I've written the following test:

describe("App", function () {

describe("ActionEvents Controller", function () {

    //basic mock lookup service which returns empty arrays
    var mockActionEventsService = {
        get: function (userId) {
            return [
                { "description": "Second Notification", "type": 4, "dateRaised": "2014-10-17T00:00:00", "hasNotified": true, "status": 0, "user": null, "id": 6 },
                { "description": "Third Notification", "type": 2, "dateRaised": "2014-10-18T00:00:00", "hasNotified": true, "status": 1, "user": null, "id": 7 }
            ];
        },
    };


    var scope;
    var log;
    var controller;

    beforeEach(module('TracerApp'));

    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        log = null;
        controller = $controller('ActionEventsCtrl as actionEventVM', { $log: log, ActionEvents: mockActionEventsService });
    }));


    it('should ensure data is present', function () {
        expect(scope.actionEventVM.ActionEvents).toJson();

    });

});

Unfortunately, when running the tests, I encountered the following error message:

TypeError: undefined is not a function
TypeError: undefined is not a function
at getActionEvents (  actionevents.controller.js: line 24:38)
at new ActionEventsCtrl (  actionevents.controller.js: line 20:19)
...

Answer №1

The reason for the error was due to my injected log object lacking the error function. I resolved this issue by adding a dummy method in log that accepts one parameter.

Answer №2

It is recommended to utilize vm.ActionEvents in place of ActionEvents at line 24 within the controller script.

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

The variable is only recognized within the function and not outside of it

Seeking assistance as a newcomer in debugging and implementing code, I have been trying various approaches to pass a base64string into JotForms for generating images in PDF format. Below is the screenshot of the error encountered. View error here The foll ...

The Javascript query is returning an [object Object] data type

I am facing an issue with a JavaScript file that is querying a SharePoint list. Specifically, the Priority drop down in the query result is displaying as [object OBJECT]. I suspect it has something to do with the var query string where I have added the &ap ...

The AngularJS promise is not resolving before the external Braintree.js script finishes loading after the HTML content has been fully

Using an external braintree.js script is necessary to generate a payment widget, and unfortunately I have no control over it. The code that needs to be included in my .html page is as follows: <div id="myClient" ng-show="false">{{myClientToken}}&l ...

Stop the ngRepeat after completing one iteration, by utilizing the "in" directive

My goal is to gather additional information about the van by using its unique id to retrieve data from the fleet it belongs to. Currently, my code successfully retrieves information about the van. However, when I uncomment certain lines of code, it breaks ...

How to invoke a Struts 2 action synchronously using JavaScript

I've been attempting to use JavaScript to make a synchronous call to a Struts 2 action. Despite finding multiple examples, none of them have worked for me. The only method that has worked so far is making an asynchronous call like this: function togg ...

Having trouble with textures when using THREE.TextureLoader instead of the outdated THREE.ImageUtils.loadTexture?

Recently, I utilized a function to apply texture on a Cylinder shape. function createElementMaterial() { THREE.ImageUtils.crossOrigin = ''; var t = THREE.ImageUtils.loadTexture( IMG_MACHINE ); t.wrapS = THREE.RepeatWrapping; t.wr ...

Struggling with UI-Grid's single filter feature when dealing with intricate data structures?

I'm currently working with UI-Grid and facing a challenge while applying a filter to some complex data using their single filter example. Initially, everything runs smoothly when I use simple selectors. However, as soon as I attempt to delve one level ...

Tips on avoiding asynchronous issues in NodeJS: Ensure task a is finished before initiating task b

I have a situation where I need to ensure that task B code only executes after task A has completed. Task A involves converting an audio file, while Task B relies on the converted audio for further processing. The issue arises because Task A saves the n ...

Change the format of the modelValue to align with the viewValue within an Angular directive

I need to customize the format of a datepicker in a form. The challenge is to display the date in 'dd/mm/yyyy' format for the user, while sending it in ISO format to an API. Below is the directive I am using: app.directive('standardDatepic ...

including a callback in a loop

I am attempting to have jQuery delete an element after it has gone through a series of other functions, however the following code executes the remove() command before the for loop runs any iterations. function waves(){ for(i=0;i<=10;i++){ ...

Using AJAX in a Django application within a RESTful ecosystem

I am new to the world of restful programming and have a Django website. My goal is to dynamically load a part of the website. Currently, my workflow is as follows: When I call a URL (such as localhost:8080/index), it routes to the Django view, which retr ...

The code seems to be malfunctioning in a separate JS file, but oddly enough, it functions properly when placed within a <script> tag

I am trying to create a loader, but I have encountered an issue where the script works when placed directly in the HTML file, but not when it is in a separate JavaScript file. Here is the script: var loader = document.getElementById("ld"); w ...

Finding the correct placement for importing 'reflect-metadata' in Next.js version 14.1.0

I am currently integrating tsyringe for dependency injection in my Next.js 14.1.0 application using the new App Router. However, I am facing an issue with its functionality when adding import 'reflect-metadata'; at the beginning of my Root Layout ...

Sending variables through methods in Vue.js is not functioning as expected

I have a straightforward form that utilizes Vue.js with Firebase (specifically the package vue-firestore). I have methods to manage user registration in Firebase, change the displayName value, and log out the current user. After this, I am registering some ...

Tips for positioning a div next to an input box when it is in focus

I am working on a scenario where I have used CSS to extend the search box when focused. The idea is that when the search box is focused, it should decrease in size and a cancel button should appear next to it. This is the CSS code I am using: .clrble .fr ...

Can you guide me on integrating an Angular 2 page into a Spring MVC Application?

I am looking to integrate index.html from an angular 2 project as the welcome page for a Spring MVC application. When running the angular 2 project with 'npm start', the components load correctly. However, without running 'npm start', t ...

Testing Angular - The Art of Mocking InjectionToken

I've been experimenting with testing an Angular service that manages SignalR connections, using the SignalR code as an InjectionToken. Check out the provider file below: // signalr-provider.ts import { InjectionToken } from '@angular/core&apos ...

Is it feasible to execute exe files within a ReactJS environment?

Hey there! I've created a Game Launcher using ReactJS for my Unity game and was wondering if it's feasible to start the game (an exe file) simply by clicking on the play button. Can anyone please advise me on this? ...

Implementing JavaScript from dojo.xhrGet within a Symfony framework

Hey there! I'm diving into the world of dojo and symfony, but I've hit a snag. I'm trying to do an Ajax reload of a section on my page, but it involves executing a JavaScript function. While I've got this down in prototype and jQuery, I ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...