4

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

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

1 回答 1

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();        
    });
});
于 2013-03-15T06:46:15.380 回答