业力错误:未知提供商

时间:2015-07-06 21:23:52

标签: javascript angularjs jasmine karma-runner

我们正试图用Karma测试我们的控制器,但是Karma一直在抱怨一个未知的提供者:

  

错误:[$injector:unpr]未知提供商:userProvider< - user

我们是否正确注入了user

我们的代码:

控制器test.js

describe('Controller', function () {
    beforeEach(module('myApp'));

    var ctrl, scope, user;

    beforeEach(inject(function ($controller, $rootScope, _user_) {
        scope = $rootScope.$new();
        ctrl = $controller('controller', {
            $scope: scope
        });
        user = _user_;
    })); 

    it("should have scope defined", function () {
        expect(scope).toBeDefined();
    });
});

app.js:

(function () {
    var myApplication = angular.module("myApp", [
        "angucomplete-alt"            
    ]);

    fetchData().then(bootstrapApplication);

    function fetchData() {
        var initInjector = angular.injector(["ng"]);
        var $http = initInjector.get("$http");

        // Get user info before app is loaded
        return $http.get('/api/user').then(function (response) {
            myApplication.value("user", response.data);
        }, function (errorResponse) {
            // Handle error case
            console.error("Obtaining user information failed when bootstrapping Angular app");
        });
    }

    function bootstrapApplication() {
        angular.element(document).ready(function () {
            angular.bootstrap(document, ["myApp"]);
        });
    }
})();

controller.js:

angular.module("myApp")
.controller("controller", ["$scope", "user", "$window",
    function ($scope, user, $window) { ... }]);

1 个答案:

答案 0 :(得分:0)

测试控制器时,应该单独进行。我只是将一个模拟的user对象放入 locals hashmap(以及$scope),例如

describe('Controller', function() {
    var ctrl, scope, user, $window;

    beforeEach(function() {
        user = {
            id: 'fake_id',
            username: 'fake_username'
        };
        $window = jasmine.createSpyObj('$window', ['some', 'methods']);

        module('myApp');

        inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            ctrl = $controller('controller', {
                $scope: scope,
                user: user,
                $window: $window
            });
        });
    });
});

示例规范可能是测试注入的user对象是否放在范围上。例如

it('puts the user onto the controller scope', function() {
    expect(scope.user).toBe(user);
});

ngMock到位的单元测试中(我假设你有),所有$http调用都通过一个不执行实际HTTP调用的模拟后端($httpBackend),除非特别指出配置为这样做。

即使你的fetchData函数在测试时运行(我怀疑它没有做其他事情你会得到一些控制台错误),它也无法检索任何数据。