Jasmine - Karma + AngularJS Tests

61 views
Skip to first unread message

Diego Freitas

unread,
May 12, 2014, 2:15:57 PM5/12/14
to ang...@googlegroups.com
Hey guys, I'm facing a problem when trying to run and create my tests ...

Here is my method's controller I'm trying to test:
$scope.findAll = function(){
        var promise = ContactService.findAll(); //promise that something will be executed
        promise.then(
            function(contacts){
                $scope.contacts = contacts;
            },
            function(reason){
                alert('Failed: ' + reason);
            });            
    }

Here is my service's method I'll call:
this.findAll = function () {
      var deferred = $q.defer(); //deferred represents a task that will be done in the future
     
$http.get(config.BASE_URL + '/contacts')
      .success(function(data, status) {
      deferred.resolve(data);
})
.error(function(data) {
console.log('Error loading Contacts: ' + data);
deferred.reject(data);
});
      return deferred.promise;
    };

 This is my script test I'm trying to run:
var myServiceMock, $httpBackend, ContactControllerMock,
        BASE_URL = "http://localhost:3000";        
    
    beforeEach(inject(function ($controller, $rootScope){
        scope = $rootScope.$new();      
        ContactControllerMock = $controller('ContactController', {
            $scope: scope
        });                     
    }));            
    
    it('should find all the contacts', inject( function (ContactService, $q, $http, config){
        // Return a successful promise from the ContactService
        var deferredSuccess = $q.defer();
        spyOn(ContactService, 'findAll').andReturn(deferredSuccess.promise);
        ContactService.findAll().then(
            function(contacts){
                $scope.contacts = contacts;
            },
            function(reason){
                alert('Failed: ' + reason);
            });  
        
        expect(ContactService.findAll).toHaveBeenCalled();
        deferredSuccess.resolve(); // resolves the promise
       
        //expect(scope.contacts.length).toBeGreaterThan(0);        
    }))    


Is not entering in the ServiceFindAll() function ... am I testing it right? What are the suggestion for the findAll test?

Thanks all in advance!

William Szeliga

unread,
May 13, 2014, 11:00:17 PM5/13/14
to ang...@googlegroups.com
I believe in your test you have to call scope.$digest() in order for the promise to be consumed (before your expect).


--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages