【问题标题】:AngularJS factory testing in Karma with Jasmine使用 Jasmine 在 Karma 中进行 AngularJS 工厂测试
【发布时间】:2013-09-29 10:07:55
【问题描述】:

我正在尝试通过 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 答案中拼凑出来。有什么指导吗?谢谢。

【问题讨论】:

    标签: javascript unit-testing angularjs jasmine karma-runner


    【解决方案1】:

    我也遇到了这个确切的错误。我的代码与我尝试测试提供者的代码类似,因此我调用模块并将其传递给配置提供者的函数。

    已解决:

    我发现问题是由于调用“inject”以将委托返回给“describe”方法。您只能使用注入将委托返回给“它”。

    例如:

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

    但这会起作用:

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

    【讨论】:

    • inject() 也可以在beforeEach() 调用中使用。
    • 所以这个问题没有解决。一些理解的人应该解释为什么浏览所有各种文档以理解它是令人困惑的。
    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多