Troubleshooting angular service jasmine test - unable to locate $http service

As I followed the tutorial at , I encountered an issue with the jasmine test provided. Despite simplifying the test to its core, it still fails to pass. Could someone point out where I might be going wrong?

The service being tested is:


var appServices = angular.module('MyApp.services', ['$http', '$rootScope']);
appServices.factory('Auth', ['$http', '$rootScope', function ($http, $rootScope) {

    var accessLevels = routingConfig.accessLevels,
        userRoles = routingConfig.userRoles,
        currentUser = { username: '', role: userRoles.public };

    function changeUser(user) {
        angular.extend(currentUser, user);
    }

    return {
        authorize: function (accessLevel, role) {
            if (role === undefined) {
                role = currentUser.role;
            }
            return accessLevel.bitMask & role.bitMask;
        },
        isLoggedIn: function (user) {
            if (user === undefined) {
                user = currentUser;
            }
            return user.role.title === userRoles.user.title;
        },
        login: function (user, success, error) {
            user.role = userRoles.user;
            changeUser(user);
            $rootScope.$broadcast('login');
            success(user);
        },
        logout: function (success, error) {
            changeUser({
                username: '',
                password: '',
                role: userRoles.public
            });
            success();
        },
        accessLevels: accessLevels,
        userRoles: userRoles,
        user: currentUser
    };
}]);

The jasmine test case is as follows:


describe('services tests', function () {

    beforeEach(function () {
        module('MyApp.services');

        inject(function (_Auth_, $httpBackend) {
            Auth = _Auth_;
            httpBackend = $httpBackend;
        });
    });

    it('should have an authorize function', function () {
        expect(angular.isFunction(Auth.authorize)).toBe(true);
    });

});

The resulting error message is:

Error: [$injector:modulerr] Failed to instantiate module MyApp.services due to:
Error: [$injector:modulerr] Failed to instantiate module $http due to:
Error: [$injector:nomod] Module '$http' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.13/$injector/nomod?p0=%24http
...

Answer №1

var appServices = angular.module('MyApp.services', ['$http', '$rootScope']);

needs to be changed to

var appServices = angular.module('MyApp.services', []);

The issue arose because $http and $rootScope are not modules, causing the error where appServices couldn't locate the $http module.

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

What method is most effective for comparing two HTML pages that contain identical content but varied markup?

I'm in search of a method to analyze two HTML pages for content. Both pages were created with React, but they have different structures. Nevertheless, the text within these pages is identical. What would be the most effective approach for comparing th ...

Generate items above the mesh

I'm currently working on a procedural terrain generation project. I have successfully generated terrain using Perlin noise, and now I want to add procedural grass generation with some specific constraints. My goal is to only generate grass within a c ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

The parent's setState does not trigger the child's componentWillReceiveProps

Within my application, there is a parent component and a child component with props connected to the parent's state. When I call setState in the parent component, the componentWillReceiveProps function of the child component does not always get trigg ...

JavaScript doesn't seem to be functioning properly within PHP

I have implemented the supersized jQuery script to incorporate sliding backgrounds on my WordPress page. Now, I aim to create unique slides for different sites and require a PHP if request. This is my code: <?php if ( is_page(array('Restaurant&a ...

Elements that are added dynamically do not contain any space between each other

I have a markup template that looks like this. <template id="unsequenced-template"> <button type="button" class="btn btn-primary railcar"></button> </template> Then, I use the following JavaScript ...

Is ASP.NET capable of displaying an expandable grid view?

After searching online, I have yet to find a solution that meets my requirements. Currently, my DB view generates the following data: --------------------------------------------------- Company | Code | Total | Available | Used | Needed ---------------- ...

Storing JSON data in a file

I am currently developing a web application for a client who has a cPanel virtual server. The limitation is that I can only use MySQL database, but I prefer storing the data in a json-like structure to make it easier to work with Angular.js on the frontend ...

Determining the elapsed time using Momentjs

I need assistance with a NodeJS project where I am trying to determine if a specific amount of time (like 1 hour) has passed since creating an object. My project involves the use of MomentJS. For example, if moment(book.createdAt).fromNow() shows 2 hours ...

Creating a horizontal line with text centered using Angular Material's approach

Implementing Angular Material, my objective is to design a horizontal line with a word positioned in the center. Similar to the one showcased here. I experimented with this code, achieving a close result, but I aim to align the lines vertically to the mid ...

Issues with IE7 related to Jquery and potentially HTML as well

I am currently working on a website project for a local charity organization, and I am encountering technical issues with compatibility in IE7. The website functions perfectly in all other browsers I have tested, and it even passes the validation process o ...

Utilizing NodeJS, Express, and the Jade template engine to insert JSON data into

While trying to follow a tutorial on NodeJS, Express, Jade, and MongoDB, I ran into a frustrating issue. Despite reading through various forum threads and attempting the suggested solutions, I still can't seem to make the POST command work. Please di ...

How to Fix Items Being Pushed Down by 'Particleground' Jquery Plugin Due to Z-Index and Positioning

I'm grappling with understanding z-index and positioning, despite reading various questions and articles on the topic. Currently, I'm attempting to incorporate a Jquery Plugin called 'Particleground': https://github.com/jnicol/particle ...

Refresh the view seamlessly using Ajax without reloading the page

When a button is clicked, the following code will run: $.ajax({ type: "POST", url: base_url+"/controller/method", data: {val: value}, success: function(data){ data = jQuery.parseJSON(dat ...

Tips for Resolving React.js Issues with setInterval

Is there a way to adjust setInterval in React so that it doesn't count faster than it should at the beginning of my program? Currently, 'var i' is being increased by 2 every second. How can I modify my code to resolve this issue? import Reac ...

I'm having trouble getting the HTML checkbox symbol to show up correctly. My goal is to create all the elements using the DOM

I am currently building all of my elements manually through the DOM tree, and I am attempting to insert a checkbox symbol in this manner: //Add date var tdDate = document.createElement("td"); tdDate.textContent = ("" + workoutList[idx].date); ...

CodeMirror version 5.62.3 is experiencing some challenges with the scrollbar functionality, editor size, and line wrapping

During my HTML/CSS/JS coding session, I encountered a challenge with CodeMirror version 5.62.3. Specifically, I was striving to make the scrollbar visible in the code editor, using C# as the language mode. However, despite setting the editor's height ...

"Troubleshooting cross-domain issues with iframes in Internet Explorer

My application is built with angularjs and we offer the option to embed it on other websites. Everything works well in IE11, but when the application is iframed onto a different domain's website, it stops working. I've tried adding <meta htt ...

Loading Web Applications Screen

My web app contains multiple tree views. Upon loading the page, I first see the unordered lists before the styling of the trees is displayed in the DOM after a brief delay. Is there a method to mask the web app with a spinner placed in the center of the s ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...