未知提供者:$ xProvider< - $ xService

时间:2014-09-14 09:50:57

标签: angularjs unit-testing

我在使用AngularJS时遇到了Karma和Jasmine的问题。我试图做的是测试一个控制器,它将从服务中为视图提供一些帖子。这是我的控制者:

app.controller('PostController', function($scope, $postService) {
    $scope.posts = $postService.getPosts();
});

这是我的测试:

describe('PostController', function(){
    var posts, $postService;

    beforeEach(module('cms'));

    beforeEach(function() {
        posts = [
            {
                title: 'Article title',
                tags: [
                    { name: 'Tag #1', link: 'posts/tagged/tag-1' }, 
                    { name: 'Tag #2', link: 'posts/tagged/tag-2' },
                    { name: 'Tag #3', link: 'posts/tagged/tag-3' }
                ],
                body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis efficitur nisi nec neque molestie ultricies. ' +
                    'Mauris facilisis libero lorem. Praesent pulvinar dictum justo, at tincidunt magna convallis at. Integer' +
                    'laoreet justo vel faucibus placerat. Sed quis elit vel ante dictum dictum. Mauris ut ullamcorper tortor.' +
                    'Phasellus finibus ex justo, eget rutrum felis lobortis tincidunt. Curabitur hendrerit elit enim, a fermentum' +
                    'odio egestas mollis.',
                author: { name: 'Dan', link: 'users/Dan-1' },
                postDate: '0 seconds ago'
            }
        ]
        postService = {
            getPosts: function() { return posts; }
        };
    })

    it('should create "posts" model with posts from PostService', inject(function($controller) {
        var scope = {},
            ctrl = $controller('PostController', {$scope: scope, $postService: postService});

        expect(scope.posts).toEqual(posts);
    }));
});

测试在这种状态下工作,但是我将无法在运行时运行控制器,因为没有明确的依赖;

  

错误:[$ injector:unpr]未知提供者:$ postServiceProvider< - $ postService

但是,如果我将控制器包装成这样的东西:

app.controller('PostController', ['$postService', inject(function($scope, $postService) {
    $scope.posts = $postService.getPosts();
}

然后控制器将在运行时工作,但在测试中,$ postService将始终为undefined来自控制器内部。

有没有人遇到过这个问题,如果有的话,我在这里错过了什么?

1 个答案:

答案 0 :(得分:1)

试试这个: 你缺少$ scope

app.controller('PostController', ['$scope', '$postService', function($scope, $postService) {
    $scope.posts = $postService.getPosts();
}]);