Karma + angular-mocks TypeError: 'undefined' is not an object (evaluating 'angular.mock = {}')

Karma + angular-mocks TypeError: 'undefined' is not an object (evaluating 'angular.mock = {}')

我正在尝试使用 Karma + Jasmine 编写单元测试,但在使用 angular-mocks 时遇到了错误。运行 grunt test 时出现以下错误:

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

谢谢!

angular-mocks.js 假定 angular.js 也已包含在内。

您还需要包括 angular.js,那么只有 angular.mocks 可以工作,否则 window.angular 将是未定义的。

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

2017 年更新和 webpack 2(但相同 angular<2)

  1. 就像@jlew 说的,angular-mocks 期望 angular 在 window

  2. 模块引用正在被 webpack 替换

所以在测试中你需要一个 header 比如:

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

并将每个全局 module 引用替换为 angular.mock.module

我在以下语句中遇到了这个错误:

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

这是由库声明中的错误顺序引起的:

karma.config.js :

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

(dependencies 是我的库列表,包含 angular.js)

我只是将 './node_modules/angular-mocks/angular-mocks.js' 移动到依赖项列表中,但是 AFTER angular.js :

像这样:

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

更进一步:

如果您查看 angular-mocks.js,您会发现它需要 angular.js 才能工作!

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

'use strict';

/* global routeToRegExp: true */
...