I'm having an issue with Karma and Jasmine while using AngularJS. What I'm trying to do is test a controller that will make some posts available to the view from a service. Here's my controller:
app.controller('PostController', function($scope, $postService) {
$scope.posts = $postService.getPosts();
});
And here is my test:
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);
}));
});
The test works in this state, however I will be unable to run the controller at runtime because there is no explicit dependency;
Error: [$injector:unpr] Unknown provider: $postServiceProvider <- $postService
However, if I wrap the controller in something like this:
app.controller('PostController', ['$postService', inject(function($scope, $postService) {
$scope.posts = $postService.getPosts();
}
Then the controller will work at runtime, however in testing, $postService will always be undefined
from inside of the controller.
Has anyone come across this issue, and if so, what am I missing here?