Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine testing AngularJS $http

I'm trying to test a REST API wrapped in an AngularJS service using Jasmine async testing. I know, I should be, and am, running tests on the API on the server, and using a mock $httpBackend to test the service, but I'd still like to know how to do async tests where I need to.

The problem I'm having is my deferreds (returned by $http) never seem to resolve. Going past the service and trying to simply use $http has the same problem. What am I doing wrong here:

describe('Jasmine + Angular + $http', function() {

    var injector; 

    beforeEach(function() {
        injector = angular.injector(['ng']);
    });

    it('can be tested', function() {

        injector.invoke(function($http) {

            var complete = false;

            runs(function() {
                $http.get('...').then(function(res) {
                    complete = true;
                });
            });

            waitsFor(function() {
                return complete;
            }, 'query to complete', 5000);

            runs(function() {
                expect(complete).toEqual(true);
            });

        });

    });

});

(I'm using grunt-contrib-jasmine to run the tests)

like image 744
nicholas Avatar asked May 29 '13 19:05

nicholas


1 Answers

The HTTP requests will not fire unless you call $httpBackend.flush().

More information can be found here: http://docs.angularjs.org/api/ngMock.$httpBackend

like image 50
Clay Avatar answered Oct 05 '22 02:10

Clay