Issue with Karma and angular-mocks: The error message "TypeError: 'undefined' is not an object (evaluating 'angular.mock = {}')" is being shown

I am facing an issue while writing unit tests using Karma + Jasmine. The problem arises with angular-mocks when I run grunt test, resulting in the following error message:

PhantomJS 1.9.8 (Mac OS X) ERROR TypeError: 'undefined' is not an object (evaluating 'angular.mock = {}') at /Users/danielbogart/Documents/coding/work/AexNav/bower_components/angular-mocks/angular->mocks.js:17 Chrome 39.0.2171 (Mac OS X 10.9.4) ERROR Uncaught TypeError: Cannot set property 'mock' of undefined at /Users/danielbogart/Documents/coding/work/AexNav/bower_components/angular-mocks/angular->mocks.js:17

This is my Gruntfile karma configuration:

    karma: {
        options: {
            frameworks: ['jasmine'],
            files: [ 
                'dom_munger.data.appjs',
                'tests/spec/*.js',
                'bower_components/angular-mocks/angular-mocks.js'
            ],
            logLevel: 'ERROR',
            reporters: ['mocha'],
            autoWatch: false, //watching is handled by grunt-contrib-watch
            singleRun: true
        },
        all_tests: {
            browsers: ['PhantomJS', 'Chrome']
        },
        during_watch: {
            browsers: ['PhantomJS']
        }
    }

Any help will be greatly appreciated. Thanks!

Answer №1

In order for angular.mocks to function properly, make sure to include angular.js in your project. Otherwise, window.angular will remain undefined.

 files: [ 
            'dom_munger.data.appjs',
            'path/to/angular.js', //<-- remember to add angular.js
            'bower_components/angular-mocks/angular-mocks.js',
            'tests/spec/*.js'
        ],

Answer №2

Updated for the year 2022 and webpack version 5 (with the same angular<2 version)

  1. As mentioned by @jlew, angular-mocks requires angular to be available on the window object

  2. The module reference is now handled differently with webpack

Therefore, in tests you should include a header like this:

import angular from 'angular';
import 'angular-mocks/ngMock';

Additionally, replace each global module reference with angular.mock.module

Answer №3

The use of angular-mocks.js relies on the prior inclusion of angular.js.

Answer №4

An issue arose with the following code snippet:

angular.mock.module( 'ui.router' )

The problem was due to a misplacement in the order of library declarations:

karma.config.js :

...
files: ['./node_modules/angular-mocks/angular-mocks.js']
   .concat(dependencies),
...

(dependencies contained a list of my libraries, including angular.js)

I resolved it by moving

'./node_modules/angular-mocks/angular-mocks.js'
into the dependencies list, but AFTER angular.js:

Updated declaration:

...
'./node_modules/angular/angular.js',
'./node_modules/angular-mocks/angular-mocks.js'
...

Furthermore:

Upon inspecting the angular-mocks.js file, it became evident that it relies on angular.js for its operation!

/**
 * @license AngularJS v1.7.5
 * (c) 2010-2018 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function(window, angular) {

'use strict';

/* global routeToRegExp: true */
...

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

Backbone.js: Navigating the Default Path Issue

I've embarked on creating my very first BB app. Progress is decent, but I've hit a roadblock. My router implementation appears as follows: var PlayersAppRouter = Backbone.Router.extend({ routes: { '': 'index', ...

What is the best way to transform an array of objects into a single string in JavaScript?

After receiving the input from req.body, it looks like this: [ { "Name": "Test_1", "Level 1": "Story_1", "Level 2": "Story_1.1" }, { "Name": & ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...

Click on the hyperlinks one by one that trigger ajax events

There is a feature on the popular social media platform reddit.com where you can load more comments by clicking a link. I understand that comments may be hidden for performance reasons, but I would like to automatically expand all comments without having t ...

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

Creating client side scripts for an ajax call to generate a Json object is simple once you understand the basics

Typically, when I make ajax calls, I request pure HTML. However, for various reasons, I require guidance on constructing a table (let's say of individuals and their information) when receiving a Json object. While I am capable of creating a table in J ...

Using the fetch method to consume a RapidAPI JSON response

Currently, I am in the process of learning React Native and have initiated a project for that purpose. In this project, I have integrated RapidAPI (link: ) to fetch necessary data. Upon hitting the API, I receive a 200OK status, but unfortunately, I am fa ...

Issue with Three.js Raycaster failing to intersect with a custom vertex shader

I'm currently working on implementing a particle system using a dedicated Vertex shader. I have provided a code example for reference: https://jsfiddle.net/dthevenin/7arntcog/ My approach involves utilizing a Raycaster for mouse picking to enable int ...

Issues with loading AngularJS prototype app page after clicking one link

As a newcomer to AngularJS, I am experiencing some strange behavior in a single page app prototype I am working on. When I select a link from the navigation, subsequent clicks only load the page if the _blank attribute is set. What could be causing the pag ...

Trigger the jQuery function based on the ID modification executed by jQuery

Is it possible to change the id of an HTML element using this function? $("#test").attr('id', 'test2'); Here is an example of the code: $("#test").click(function() { $("#test").attr('id', 'test2'); alert(& ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

Creating a function in a JavaScript module that can be exported to the window namespace

One of the goals of modules is to protect variables and functions defined inside from being accessed outside the script. However, if you want to export a specific function for global use, there are ways to accomplish this. Merely assigning it to the window ...

Setting a variable equal to user input

When using a jQuery script, the elements for the details are dynamically created inside a jQuery function. However, there seems to be an issue with assigning the value from the variable "startLocation" to the input "detail_startLocation[]". Only the firs ...

Having trouble retrieving data from getStaticProps

I'm currently developing a project using next.js and I am attempting to fetch a list of gyms in the getStaticProps function. Here is my code snippet: import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet"; import { useState } ...

tips on displaying textbox content on a php webpage

I have a piece of code where, when text is entered into a textbox and the add attribute button is clicked, the entered value is displayed on the page twice. One appears in the first row of a table, and the other appears in the first row of a second table. ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

The wordpress jquery dependency is failing to respond

After converting an HTML ecommerce template into WooCommerce, I am experiencing issues with the functionality. The Nivo slider and some other product features are not working properly. It seems like they are having trouble finding WordPress jQuery, even th ...

JavaScript method to clear a variable

Can JavaScript prototype be used to add a method to a variable that is undefined? For instance, we can use the following code: var foo = "bar"; String.prototype.doTheFoo = function(){ console.log("foo is better than you"); }; foo.doTheFoo(); This c ...

A JavaScript alert function that triggers no matter the return value

An alert is being sent by a function when a radio box's value returns as null, even though it should have a value that is not null. The issue lies in another function on the page that hides the tables where these radios are located, making it difficul ...

What is the process of incorporating a Higher-Order-Component in React?

I've been working on setting up a Higher Order Component (HOC) in React to enable text selection detection for any Input component. However, I seem to be missing a key piece of the puzzle in putting it all together. Initially, I followed an article t ...