因果报应错误:未知提供者

Karma error: unknown provider

本文关键字:提供者 未知 错误 因果报应      更新时间:2023-09-26

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

错误:[$injector:unpr] Unknown provider: userProvider <- user

我们注入user正确吗?

我们的代码:

controller-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) { ... }]);

在测试控制器时,应该单独进行测试。我将简单地将模拟的user对象放入locals哈希映射中(与$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调用都经过一个模拟后端($httpBackend),该后端不执行真正的HTTP调用,除非特别配置为这样做。

即使您的fetchData函数在测试时运行(我怀疑它没有这样做,否则您会得到一些控制台错误),它也不会检索任何数据。