Error: The JavaScript variable 'undefined' is being used as a function, which is incorrect. This error occurs when trying to execute the function `mockBackend

I am currently working on unit testing an AngularJS controller using Karma and Jasmine.

Below is the test suite I have created:

describe('Controllers', function(){
    var $scope, ctrl;
    beforeEach(module('curriculumModule'));
    describe('CreateCurriculumCtrl', function(){
        var mockBackend, location;
        beforeEach(inject(function($rootScope, $controller, _$httpBackend_, $location){
            mockBackend = _$httpBackend_;
            location = $location;
             $scope = $rootScope.$new();
             ctrl = $controller('CreateCurriculumCtrl', {
                    $scope: $scope
             });
        }));

        it('should successfully save the curriculum', function(){
            mockBackend.expectPost('bignibou/curriculum/new');
            $scope.saveCurriculum();
            mockBackend.flush();
            expect(location.path()).toEqual("/");
        });

    });
});

The output from running karma start is as follows:

PhantomJS 1.9.2 (Linux) Controllers CreateCurriculumCtrl should successfully save the curriculum FAILED
    TypeError: 'undefined' is not a function (evaluating 'mockBackend.expectPost('bignibou/curriculum/new')')
        at /home/julien/Documents/projects/site-garde-enfants/bignibou/karma/test/spec/curriculum.test.js:16
PhantomJS 1.9.2 (Linux): Executed 2 of 2 (1 FAILED) (0.203 secs / 0.023 secs)

I'm struggling to understand why this error is occurring, given that I have correctly included the angular-mock.js file in my karma configuration:

// list of files / patterns to load in the browser
files: [
   '../src/main/webapp/js/libs/jquery-1.10.2.js',
   '../src/main/webapp/js/libs/angular.js',
   '../src/main/webapp/js/libs/bootstrap.js',
   '../src/main/webapp/js/plugins/angularui.select2.js',
   'test/vendor/angular-mocks.js',

  '../src/main/webapp/js/custom/curriculum.js',
  'test/spec/curriculum.test.js'      
],

If anyone could provide some assistance, it would be greatly appreciated.

Edit: Here is the code for my controller:

function CreateCurriculumCtrl($scope, $http, $location, select2Options){

    $scope.formData={};

    $scope.select2Options = select2Options; 

    $scope.saveCurriculum = function(){
        $http.post('bignibou/curriculum/new', $scope.formData).success(function(data) {
            if(data.status=="OK"){}
            if(data.status=="KO"){}
            $location.path("/");
        });
    };
}

Answer №1

On line 16, I made the following change:

Instead of

mockBackend.expectPost('bignibou/curriculum/new');

I updated it to

mockBackend.expect('POST','bignibou/curriculum/new').respond({});

This adjustment resolved the issue at hand...

edit: expectPOST would have also been a valid solution... It was simply a case sensitivity error that caused the initial problem...

Answer №2

Chances are your scenario will resemble the following:

var x = {};
x.y();

The function x.y is not defined, so attempting to execute it will result in an error.

On line 16, we have $scope.saveCurriculum(), but is $scope.saveCurriculum actually undefined?

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

Incorrect format for a date in AngularJS

I have a time input field where I am receiving the date and time format 'Thu Jan 01 1970 12:59:00 GMT+0530 (India Standard Time)', but I only want to display the time. Is there an issue with the time picker in AngularJS? Can anyone help me resolv ...

Using JavaScript closures together with a timeout in the onKeyUp event

My goal is to add an onKeyUp event to all input fields within a form using closures. The array fields holds the names of the fields that need this event, while the array ajaxFields contains the names of fields requiring ajax validation. function createEve ...

Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other? Here's the Scenario: I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Stor ...

Different Option for Single-spa

We currently possess a vast enterprise application developed in angularjs. However, we are now faced with the task of transitioning to angular. Consequently, we have dismissed the option of employing the recommended "ngUpgrade" hybrid approach. Hence, we ...

Retrieve the next 14 days starting from the current date by utilizing Moment.js

Looking to display the next 14 days in a React Native app starting from today's date. For example, if today is Friday the 26th, the list of days should be: 26 - today 27 - Saturday 28 - Sunday 01 - Monday 02 - Tuesday ............ 12 - Friday Is ther ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

Initiating a horizontal scroll menu at the center of the screen: Step-by

I need assistance setting up a horizontal scrolling menu for my project. The requirement is to position the middle button in the center of the .scrollmenu div. Currently, I am working with HTML and CSS, but open to suggestions involving javascript as well ...

Using CSS to automatically adjust the width of a child div based on its content, rather than stretching it to fill the entire

I'm currently facing an issue with my CSS. Apologies for the vague title, but I'll do my best to explain it here. My problem lies within a parent wrapper div that is centered on the page. Within this wrapper, there is another child div containing ...

Difficulties with integrating tooltips into SVGs

Being a minimalist, I am facing restrictions while working on a website. I desire interactive tooltips to appear when users hover over specific sections of my SVG. However, I also want to incorporate this interactivity within the SVG itself. The challenge ...

Ways to verify if TypeScript declaration files successfully compile with local JavaScript library

I have recently updated the typescript definitions in HunterLarco/twitter-v2, which now follows this structure: package.json src/ twitter.js twitter.d.ts Credentials.js Credentials.d.ts My goal is to verify that the .js files correspond correctly ...

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...

Tips for modifying the max length value in Angular

I'm just starting out with Angular and I'm trying to alter the maxlength property from 300 to 140 upon clicking a button. The buttons are generated using ng-repeat and only the first one should change the value to 140, while the others should rem ...

Can you explain the meaning of "|| [];"?

Can you explain the significance of || [] in this code snippet and provide some insight into why it's included? getPair: function() { return this.props.pair || []; }, ...

What could be the reason for the unexpected outcome when checking if display is equal to "none"?

I have a JavaScript function called "display()". I want to hide my navigation menu on click, but it is not working properly - it just blinks. I am looking for a solution that uses only JavaScript and does not involve querySelector. function display() { ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Froala text area is unexpectedly visible when I attempt to cover it with a partially see-through mask

The website I'm currently developing features a semi-transparent overlay that dims the screen with a light-colored message displayed on top. This overlay and message are shown whenever there is a background process running. Everything was running smoo ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...