Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Jasmine Unit Tests

I have the following unit tests, and for some reason the second test makes other tests fail.

beforeEach(inject(function ($rootScope, _$httpBackend_, $controller, $location, mockedResource) {
    scope = $rootScope.$new();
    httpBackend = _$httpBackend_;
    locationService = $location;

    ctrlDependencies = {
        $scope: scope, 
        resource: mockedResource,
    }

    var ctrl = $controller('myController', ctrlDependencies);
}));

it('should redirect to a new page', function() {
    scope.pageRedirectFunction();
    expect(locationService.path()).toBe('/newpage')
});

it('should delete an epic resource', function() {
    httpBackend.expectGET('/api/v1/epic/1').respond({});
    httpBackend.expectDELETE('/api/v1/epic/1').respond({});

    // Run the deletion function
    scope.deleteEpicResource()

    httpBackend.flush() // This line seems to be the rebelious one

    expect(scope.epicResources.length).toEqual(0)
})

I have managed to figure out the line that seems to cause the errors, and it's the httpBackend.flush() line. Why is the flush function causing strange behaviour?

The actual error I get from running the command karma start in the terminal, is:

 Delaying execution, these browsers are not ready: Chrome 29.0 ....

after a little while, the Chrome session then crashes.

like image 209
Sneaksta Avatar asked Nov 01 '22 15:11

Sneaksta


1 Answers

A little-known tip about testing/mocking async requests with jasmine and AngularJS:

If you're not explicitly calling the request in your test (i.e. calling it through another function), the request won't be digested by Angular, so it makes it seem as if the request never fired (when you call flush())

Try running scope.$digest() before your httpBackend.flush() call, that may do the trick. See this thread for more information.

like image 171
robert.bo.roth Avatar answered Nov 08 '22 09:11

robert.bo.roth