Karma和Jasmine中的AngularJS工厂测试

6

我正在尝试使用Karma通过Jasmine测试我的AngularJS应用程序。 我收到了这个错误(至少,这是最新的错误):

Uncaught TypeError: Cannot read property '$modules' of null
    at /Users/benturner/Dropbox/Code/galapagus/app/static/js/angular-mocks.js:1866

以下是我的 karma.conf.js 文件:

files: [
        'static/js/jquery.min.js',
        'static/js/angular.min.js',
        'static/js/angular-mocks.js',
        'static/js/angular-resource.min.js',
        'static/js/angular-scenario.js',
        'static/js/angular-loader.min.js',
        'static/js/momentous/ctrl_main.js',  // contains all my app's code
        'test/momentous.js'
],

这是我的测试:

(function () {
    "use strict";

    var controller = null;
    var scope = null;

    describe("Services", inject(function($rootScope, Moments) {
        var mockedFactory, moments, flag, spy;
        moments = [{name: 'test'}];

        beforeEach(module('momentous', function($provide) {
            scope = $rootScope.$new();

            $provide.value('$rootScope', scope);

            mockedFactory = {
                getList: function() {
                    return moments;
                }
            };
            spy = jasmine.createSpy(mockedFactory.getList);

            $provide.value('Moments', mockedFactory);
        }));

        it('should return moments from the factory service', function() {
            runs(function() {
                console.log(scope.getList);
                flag = false;
                setTimeout(function() {
                    scope.getList();
                    flag = true;
                }, 500);
            });

            waitsFor(function() {
                return flag;
            }, "The call is done", 750);

            runs(function() {
                expect(scope.moments).toEqual([{name: 'test'}]);
                expect(spy).toHaveBeenCalled();
            });
        });
    }));

}());

所以,我的目的是模拟工厂服务并检查它是否返回一个对象数组并将其设置为$scope变量。
这里还有一个异步调用,所以我不得不使用runs()和waitsFor()。
我仍然不明白我是如何注入我的$scope以便进行测试的,而且由于angular-mocks.js现在给我一个错误,我感觉我离解决问题越来越远,而不是更近。
我从各种文档、指南和stackoverflow答案中拼凑了这个,需要指导吗?谢谢。
1个回答

10

我也遇到了完全相同的错误。我的代码很相似,我正在尝试测试一个提供程序,所以我调用模块并传递一个配置提供程序的函数。

已解决:

我发现问题是因为调用“inject”返回“describe”方法的委托。你只能使用inject来返回到“it”的委托。

例如:

describe('something', inject(function(something) {}));  // will throw the $module is null error

但这样做是可行的:

it('something', inject(function(something) {}));  // works :)

inject()也可以在beforeEach()调用中使用。 - Alejandro García Iglesias
3
这个问题尚未得到解决。需要理解的人应该解释一下为什么,因为阅读所有不同的文档以理解它会让人感到困惑。 - Léon Pelletier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接