I am quite new to testing in Angular JS and am running into some issues when unit testing a controller (I'm using Karma and Jasmine).
I know best practice is to test resource factories and controllers separately, but, for now, I'm trying to test them all at once since my controller has functions that make calls to these resources.
angular.module('myApp.controllers')
.controller('myDocumentsController', ['documentResourceFactory', '$scope', function(documentResourceFactory, $scope) {
$scope.queryDocuments = function(){
$scope.userDocuments = documentResourceFactory.query($scope.queryParams(), function(){
$scope.fetchingDocuments=false
})
};
$scope.queryParams = function() {
if($scope.feedItem) {
return { "feed_item_id": $scope.feedItem.id }
} else {
return { "entry_id": $scope.entry.id }
}
};
}])
And here is the test I'm building for this controller that I can't seem to get to work:
describe('myDocumentsController', function(){
var $scope, $httpBackend, $rootScope, $controller, documentResourceFactory;
beforeEach(angular.mock.module('myApp'));
beforeEach(angular.mock.inject(function(_$rootScope_, _$controller_, _$httpBackend_, _documentResourceFactory_){
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$controller = _$controller_
$httpBackend = _$httpBackend_;
documentResourceFactory = _documentResourceFactory_
$controller('myDocumentsController', {$scope: $scope});
}));
describe('called when looking at feed item documents', function(){
beforeEach(function(){
$scope.feedItem = {
"id": 3533669,
"description": "Exhibit",
"published_at": "2015-02-04T15:14:51.000Z",
"published_at_to_i": 1423062891,
};
});
//PASSING
it('should be a feedItem on the scope', function(){
expect($scope.feedItem).not.toBeNull();
});
//PASSING
it('should have queryParams() returning "feed_item_id" when there is a feed item on the scope', function(){
expect($scope.queryParams()).toEqual({"feed_item_id": 3533669});
});
// THIS TEST IS NOT PASSING
it('should return a list of documents associated a feed item', function(){
$httpBackend.when('GET', 'http://ift.tt/16H1Z4p').respond([{}, {}]);
$scope.$apply(function() {
$scope.queryDocuments()
});
expect($scope.userDocuments.length).toEqual(2);
$httpBackend.flush();
});
});
The issue here is that no matter what I do, the $httpBackend never gets hit and; therefore, never responds with the two empty objects. I get an empty array when I test this and it tells me that it "Expected 0 to equal 2". So it seems that the test is running fine, I just can't seem to get the response from the $httpBackend. All of this code works well when I run it on the development server.
What am I doing wrong here? Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire