Testing of AngularJS Controller using Jasmine and Karma: "Error - Unable to read property 'then' of undefined"

I am currently attempting to perform unit testing on an AngularJS controller and encountering an error message while running Karma:

Cannot read property 'then' of undefined

I am unsure of what I am doing incorrectly. This is my first time conducting tests.

Here is the controller code:

angular
    .module('my')
    .controller('MyCtrl', MyController);

MyController.$inject = ['$scope', 'myFactory'];

function MyController($scope, myFactory) {

    $scope.thingy = {};

//[..]
    function getThingys() {
        myFactory.getThingys(function () {}).then(function (data) {
            //SUCCESS
            $scope.thingy = data;
        });
    } 
}

And here is the test code:

var scope;
var controller;
var mockedMyFactory;

beforeEach(module('my'));

beforeEach(module('my', function ($provide) {
    mockedMyFactory = {
        getThingys: jasmine.createSpy()
    };
    $provide.value('myFactory', mockedMyFactory);
}));

beforeEach(inject(function ($controller, $rootScope, myFactory) {
    scope = $rootScope.$new();
    controller = $controller('MyCtrl', {
        $scope: scope, myFactory
    });
}));

describe('this', function () {
    it('is a dummy spec', function () {
        expect(2 + 2).toEqual(4);
    });
});

Answer №1

To ridicule the system:

 let $httpBackend;
 let myFactory; 

 beforeEach(angular.mock.inject(function ($injector) {    
        // Setting up the mock http service responses
        $httpBackend = $injector.get('$httpBackend');

        // Defining backend for all tests
        myFactory= $injector.get('myFactory');

        $httpBackend.when('GET', 'url for call').respond({mock data});
}

 afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

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

Custom variables can be passed to subscription buttons through Paypal

I am currently working on finding a solution to passing custom variables when applying for a subscription for my created web service. The code on the front end that I have implemented so far is as follows: const createSubscription = (data, actions) => { ...

Send multiple input groups using Ajax POST requests

I need help setting up a form with 4 groups of checkboxes for refining search results. My goal is to send an array for each checkbox group that contains the IDs of the currently selected checkboxes. $.ajax({ url: "/stay_in_belfast/accommodation", t ...

Unable to set up Angular 1.5 component router

Struggling to incorporate the Angular 1.5 component router into a new project has been quite challenging for me. According to the instructions provided at https://docs.angularjs.org/guide/component-router, running the following command should do the trick: ...

Having trouble accessing the href attribute after clicking on an <a> tag with JavaScript

My issue lies in retrieving the href attribute of <a> tags when there is another element nested inside them: Here's the code snippet: const $elems = document.querySelectorAll('.content-container a') var elems = Array.from($elems) e ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

What are the best techniques for creating animations in AngularJS?

I've been trying to figure out how to animate in AngularJS by searching online, but I haven't found a perfect solution yet. html <span class="sb-arrow down" ng-click="hideSampleList($event)"></span> ...

Creating an uncomplicated search bar that dynamically adjusts values based on its function

Summing it up, there is a div situated within my app.component.html: <div class="col-lg-6 search-div"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for..."> <span class="input-group-b ...

Preserve the visibility of a text input form while the checkbox is selected

Within my HTML code, there is a form that includes a checkbox labeled "other." When this checkbox is selected, a textbox will appear. If the user types in text and submits the form, the textbox disappears, but the checkbox remains checked (as saved in loca ...

Exploring AngularJS: testing asynchronous $scope functions

I'm currently testing a controller method that interacts with the $scope object. This method initiates an asynchronous call and receives a promise in return. Once the promise is resolved, the resulting data is assigned to a variable within the $scope. ...

The discovery of a commitment in the statement. The automation of unwrapping promises within Angular statements has been phased out

Struggling with errors while setting up a new AngularJS project. Here is the code for my app and controller; var app = angular.module('myApp', ['localytics.directives']) .config(['$parseProvider', function ($parseProvide ...

Loop stops after completing one iteration

I am currently working on a program that automatically generates ASCII text based on input numbers. Essentially, when a number is provided as input to the function, it will be displayed as magnified ASCII text. For example, an input of 0123456789 would gen ...

Having trouble displaying values from nested JSON in a datatable

Response from server : ["{\"CLIENT\":[{\"tranche\":\"1-4\",\"prix\":\"65.96\",\"currency\":\"E\"}],\"DISTRIBUTEUR\":[{\"tranche\":\"1-4\",\"prix\ ...

Update the .erb code with Ajax after successfully creating the object

What is the best way to use Ajax in Rails 4 to automatically refresh the code in ".erb" files after successfully creating a new "Box"? The relevant file is located in: views/modifications/show.html.erb <tbody id="boxes_count"> <% @modificat ...

Having trouble with the $.post method not loading my PHP file in my

I followed a tutorial on YouTube to copy the code, adjusted the database connection and SELECT items to fit my existing DB, but I'm struggling to get the JS file to load the PHP file. When I use Chrome's "inspect" tool, it shows that the JS file ...

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

What is the best way to update my logo and incorporate a colored border at the bottom of my fixed header while the user is scrolling down?

After spending countless hours researching online, I've been struggling to implement header effects on scroll without using JavaScript. My goal is to achieve a simple effect where the header reduces in height, the logo changes, and a colored border is ...

Filtering Key Presses in Quasar: A Comprehensive Guide

Seeking Assistance I am looking to integrate an "Arabic keyboard input filtering" using the onkeyup and onkeypress events similar to the example provided in this link. <input type="text" name="searchBox" value="" placeholder="ب ...

Limit access to all pages, with the exception of the home page, in Django

During the development of my Django application, I organized the functionality into sub-functions and implemented them in individual apps. To display results on the homepage instead of redirecting to a sub-function app page, I utilized ajax and JavaScript. ...

Convert a JSON object into a string using Node.js

Here is my code snippet: app.get('/status',function ( req,res) { var data = { "error": 1, 'data status': "" }; connection.query("SELECT * from status", function (err, rows, fields) { ...

The ngModel directive automatically clears the checkbox's Checked status

Currently, my Angular code is set up to validate a checkbox using ng-model: <input type="checkbox" name="news1" value="news1" ng-model="news" <c:if test="${xxxx == yes'}">checked="checked"></c:if>> <label ng-click="news1();"&g ...