Patrick
Patrick

Reputation: 8063

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();
  });
});

Upvotes: 4

Views: 2884

Answers (1)

zbynour
zbynour

Reputation: 19817

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();        
    });
});

Upvotes: 9

Related Questions