Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing broadcasts in AngularJS and Testacular

I'm using the angular-http-auth module which intercepts 401 responses. This module broadcasts event:auth-loginRequired if there is a 401 response which can be received with $on(). But how can I test this?

beforeEach(inject(function($injector, $rootScope) {
  $httpBackend = $injector.get('$httpBackend');
  myApi = $injector.get('myApi');
  scope = $rootScope.$new();
  spyOn($scope, '$on').andCallThrough();
}));
describe('API Client Test', function() {
  it('should return 401', function() {
    $httpBackend.when('GET', myApi.config.apiRoot + '/user').respond(401, '');
    myApi.get(function(error, success) {
      // this never gets triggered as 401 are intercepted
    });
    scope.$on('event:auth-loginRequired', function() {
      // This works!
      console.log('fired');
    });

    // This doesn't work
    expect($scope.$on).toHaveBeenCalledWith('event:auth-loginRequired', jasmine.any(Function));

    $httpBackend.flush();
  });
});
like image 648
Patrick Avatar asked Jan 14 '23 23:01

Patrick


1 Answers

Based on your comment I think you don't need any expect($scope.$on).toHaveBeenCalledWith(...); since it makes sure that something really listens the event.

In order to assert the event is fired you have to prepare everything necessary and then perform the action leading to the event broadcast. I guess the spec could be outlined in following manner:

it('should fire "event:auth-loginRequired" event in case of 401', function() {
    var flag = false;
    var listener = jasmine.createSpy('listener');
    scope.$on('event:auth-loginRequired', listener);
    $httpBackend.when('GET', myApi.config.apiRoot + '/user').respond(401, '');

    runs(function() {
        myApi.get(function(error, success) {
            // this never gets triggered as 401 are intercepted
        });
        setTimeout(function() {
            flag = true;
        }, 1000);
    });

    waitsFor(function() {
        return flag;
    }, 'should be completed', 1200);

    runs(function() {
        expect(listener).toHaveBeenCalled();        
    });
});
like image 166
zbynour Avatar answered Jan 24 '23 11:01

zbynour