Trouble injecting factory into controller using Jasmine and requireJS

I'm encountering some difficulties when trying to inject my factory into testing spec. My setup involves using requireJS to inject controllers and factories.

    define(['controller', 'loginFactory', 'angular', 'angularMocks'],

      function(ctrl, loginFactory, angular){

        var scope,
            OnBoardingCtrl;

        describe('Controller: OnBoarding', function () {

          beforeEach(angular.mock.inject(function ($rootScope, $controller, $location) {

            angular.module('app');

            scope = $rootScope.$new();

            OnBoardingCtrl = $controller(ctrl, {
              '$scope': scope,
              'loginFactory': loginFactory,
            });


          }));

      it('Should verify endpoint', inject(function ($http, $httpBackend) {

        var successCallback = jasmine.createSpy();
        var url = 'login?un=test&pw=test';

        var response = {"token":1}

        $httpBackend.expectGET(url)
          .respond(200, response);

        $http.get(url).success(successCallback);

        expect(successCallback).not.toHaveBeenCalled();

        $httpBackend.flush();

        expect(successCallback.token).toBe(1);

      }));
    });
  }
);

But I'm consistently receiving a TypeError: 'undefined' is not an object (evaluating 'successCallback.token). For context, here is how my LoginFactory is structured:

  var LoginFactory = function ($q, $http) {

    return {
      getData: function (url) {
        var deferred = $q.defer();
        $http.get('http://local/'+url)
          .then(function () {
            deferred.resolve(true);
          }, function () {
            deferred.resolve(false);
          });

        return deferred.promise;
      }
    };

  };

  LoginFactory.$inject = ['$q', '$http'];
  factories.factory('LoginFactory', LoginFactory);

  return LoginFactory;

Any help or advice would be greatly appreciated!

Answer №1

It appears that the issue lies in the successCallback.token line of your code. The reason for this is that jasmine.createSpy() creates a function without any knowledge of the token from your mock response generated by $httpBackend. As stated in the official documentation,

When no function is present to spy on, jasmine.createSpy can generate a "bare" spy. This spy functions like any other spy, keeping track of calls and arguments, but it lacks an actual implementation. Spies are JavaScript objects and can be utilized as such.

To resolve the error, you can remove the line

expect(successCallback.token).toBe(1);
. If you wish to validate the mock response from $httpBackend, you should do so within the success callback of $http or using the then method of the promise object, as shown below:

 $http.get(url).success(function(response){
     expect(response.token).toBe(1);
 });

Please note that the example code has been adjusted to illustrate the point. In practice, it is recommended not to separately write the HTTP call in your test case; instead, invoke the actual function that initiates the HTTP call and validate the expectations.

For further information on $httpBackend, refer to this resource.

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

Combine multiple form values to calculate the total sum

To tackle the issue of adding up independent totals in a PHP foreach loop and displaying a grand total, we need to modify the JavaScript function. Right now, the function works fine for each line, but doesn't calculate the grand total correctly. Let&a ...

The controller in AngularJS is not defined

I'm currently developing a small Angular project where I am utilizing the bootstrap calendar by mattlewis92. However, I am running into issues with my controller. Below is my .js file: 'use strict'; var app = angular.module('Calendri ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

Is the JQuery Mobile .page() method triggering an endless loop?

Creating a dynamic listview with data from an AJAX response has been successful, however, when using JQM's .page() function on it, it appears to enter an infinite loop where the listview keeps getting appended indefinitely. I'm unsure if this is ...

Is it possible to deactivate an element based on a specific string present in the URL?

<div class="custom-class1"> <div class="custom-class2" id="custom-id1">hello 1</div> <div class="custom-class3" id="custom-id2">hello 2</div> <div class="custom-class4" id="custom-id3">hello 3&l ...

How does Socket.IO manage the functions that are provided to it?

This project involves the use of angularJs, nodeJs, and mongoDb. On the client side, I have the following code: webSocket.emit('createNode', node, function(node){ /* ^ */ /* ...

Transmitting occasional feedback from ASP.NET Web API function to jQuery AJAX

I am currently working on a project that requires sending intermittent status responses from a Web API method back to a jQuery AJAX call in order to display progress in the UI. https://i.sstatic.net/Y6R4w.png The process involves the jQuery AJAX calling ...

Select the correct nested div with the same name by clicking on it

My problem involves nested div elements with the same class. For example, I have a Panel inside another Panel. However, when I click on the inner panel, it is actually the outer panel that triggers the $(".panel").click function. What I need is for the ...

Woops! Looks like there's an issue - the property 'url' is not defined and cannot be

I am currently working on fetching data from a REST API using angular2, and everything seems to be going smoothly. However, I have encountered an error that only appears in the console when calling {{content.img.url}}. Interestingly, the code executes fine ...

Display all y-axis values in the tooltip using HighCharts

I utilized a chart example from http://www.highcharts.com/demo/column-stacked When you hover the mouse over a column, it displays the value of the y axis being hovered and the total value. I am interested in having the tooltip show the values of all 3 y ...

Incorporate a corner box feature to bring attention to the typed.js functionality

I have successfully integrated typed.js into my project and now I am looking to replicate the highlighted text with an excel-like box in one corner. I've managed to get the text typing out while also adding an SVG for the box in HTML, but I'm hav ...

Step-by-step guide on sending a JSON object to a web API using Ajax

I have created a form on my website with various fields for user entry and an option to upload a file. After the user fills out the form, my JavaScript function converts the inputs into a JSON file. I am attempting to send this generated JSON data along wi ...

JavaScript code that uses jQuery does not function properly on an HTML form

Hello everyone, I am having trouble with some JavaScript code. Here is what I have: $(document).ready(function(){ $(".replyLink").click(function(){ $("#form-to-"+this.id).html(htmlForm()).toggle(500); return false; }); function htmlForm(){ var htm ...

Issue with deploying NEXT.JS due to a failure in the build process caused by next lint

Issue I have been encountering deployment failures on Vercel due to lint errors in test files within my git repository. Despite following the recommendations from the Vercel documentation for ESLint settings, the issue persists. According to Vercel' ...

Verify that the computer is connected to the Internet by sending an ajax request to Google

Whenever I need to test my internet connection, I rely on the following code snippet: const checkInternetConnection = () => { $('input').ajaxError(function(){ alert("failed"); }); $.get('http://www.google.com', f ...

What is the correct way to pass a table record value to a jQuery function?

Within my php code, there is this snippet: echo "<td><button id='pausebut_{$record['idTrack']}' name='StopButton' type='Button' value='{$record['PreviewURL']}'>Stop</button> &l ...

Choose a single checkbox to select all options within a bs-table row

After successfully using bs-tables to pass selected rows through checkboxes, I am now faced with the challenge of sending data from all rows when just one checkbox is selected. The code below depicts my current approach for passing data of single and mul ...

Attempting the how-to-npm exercise, however, unable to locate the designated directory for the task

You can access the how-to-npm guide on GitHub by visiting: https://github.com/workshopper/how-to-npm https://i.sstatic.net/nyjrk.png ...

Customize the yellow background color of Safari's autofill feature by following these simple

When I open this image in Safari, this is what I see: https://i.stack.imgur.com/KbyGP.png However, this is the code I have: https://i.stack.imgur.com/4wEf0.png References: How to Remove WebKit's Banana-Yellow Autofill Background Remove forced ye ...

Guide to finding your way to a specific section in React

I attempted to navigate to a particular section within a page. I also tried to include an id in the component, but it didn't function as expected <Login id ="login_section > ...