13
votes

I'm trying to write unit tests using Karma + Jasmine, but running into an error with angular-mocks. When running grunt test I get the following error:

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

Gruntfile karma config:

    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']
        }
    }

Thanks!

4
You would need to include angular.js as well, then only angular.mocks will work else window.angular will be undefined. - PSL

4 Answers

20
votes

You would need to include angular.js as well, then only angular.mocks will work else window.angular will be undefined.

 files: [ 
            'dom_munger.data.appjs',
            'path/to/angular.js', //<-- include angularjs
            'bower_components/angular-mocks/angular-mocks.js',
            'tests/spec/*.js'
        ],
4
votes

update for 2017 and webpack 2 (but same angular<2)

  1. like @jlew said, angular-mocks expects angular on the window

  2. module reference is being replaces by webpack

So in tests you need an header like:

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

and replace each global module reference with angular.mock.module

3
votes

angular-mocks.js presumes that angular.js has been included as well.

0
votes

I had this error on the following statement :

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

This was caused by a wrong order in libraries declaration :

karma.config.js :

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

(dependencies was the list of my libs and containing angular.js)

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

Like this :

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

To go further :

If you look at angular-mocks.js you can see it needs angular.js to work !

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

'use strict';

/* global routeToRegExp: true */
...