在AngularJS和Testacular中测试广播

时间:2013-03-14 13:03:39

标签: testing angularjs jasmine karma-runner

我正在使用拦截401响应的angular-http-auth模块。如果有401响应可以使用$ on()接收,则此模块广播event:auth-loginRequired。但是我该怎么测试呢?

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

1 个答案:

答案 0 :(得分:9)

根据您的评论,我认为您不需要任何expect($scope.$on).toHaveBeenCalledWith(...);,因为它可以确保某些内容真实地监听该事件。

为了断言事件被触发,你必须准备好所有必要的东西,然后执行导致事件广播的动作。我想这个规范可以通过以下方式概述:

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