【问题标题】:Jasmine unit test for AngularJS controllerAngularJS 控制器的 Jasmine 单元测试
【发布时间】:2014-06-09 21:28:50
【问题描述】:

我正在尝试使用 Jasmine 在 AngularJS 中对控制器进行单元测试。控制器的语法与我能找到的大多数文档略有不同,我收到了这个错误...... http://errors.angularjs.org/1.2.15/$injector/unpr?p0=propertiesProvider%20%3C-%20properties

控制器...

myApp.controller('myController', function($scope, $rootScope, param) {

    param.info.get().then(function(example){
        //...
    });

});

测试js...

describe('myApp', function() {
    var $scope, $rootScope, param, createController, properties;
    beforeEach(module('myApp'));

    debugger; //runs

    beforeEach(inject(function($injector) {

        debugger; //doesn't run

        $rootScope = $injector.get('$rootScope');
        properties = $injector.get('properties');
        param = $injector.get('param');
        $scope = $rootScope.$new();
        var $controller = $injector.get('$controller');

        createController = function() {
            return $controller('myController', {
                '$scope': $scope,
                '$rootScope':$rootScope,
                'properties':properties,
                'param':param,
            });
        };
    }));

    var a;

    it('should pass this basic test no matter what', function() {
        a = true;

        expect(a).toBe(true);
    });
});

参数定义...

myApp.factory("param", function($http) {
return {
    info: {
        get: function() {
            return $http.get(myApp.url("/param/info")).then(function(response) {
                return response.data.data;
            });
        }
    }
}

myApp.run...

myApp.run(['$http', '$rootScope', 'properties', function($http, $rootScope, properties){
...
}]);

【问题讨论】:

  • 您的param 定义如何?您在代码的哪个位置注入了properties 服务?
  • 确保包含参数服务的文件由 karma 加载
  • @ExpertSystem 我添加了参数定义。我不认为我在任何地方注入属性,你能解释一下吗?
  • @j_buckley:根据您得到的错误,似乎在某处注入了properties,错误是由于Angular无法找到properties服务的实现.在您的代码库中搜索“属性”。
  • @ExpertSystem 好的,我明白你的意思了。我用属性注入更新了代码。但是,我添加了两个调试器,但第一个运行,第二个不运行。你看到beforeEach(inject(function($injector) { 有问题吗?我还包括了 myApp.run,它看起来像 properties 来自。

标签: angularjs unit-testing controller jasmine


【解决方案1】:

如果您仔细查看错误,它会在propertiesProvider 中显示错误,您在测试中注入了properties,因此它正在寻找不存在的propertiesProvider。所以它会抛出错误。

如果 propertiesangular Service 并且您将其注入到您的控制器中,在测试时您不需要再次将该服务注入您的测试,角度模拟会处理这个问题。

我建议你使用 npm 包generator-yosapy 来引导你的控制器测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2014-04-12
    相关资源
    最近更新 更多