在AngularJS和Testacular中测试广播

前端之家收集整理的这篇文章主要介绍了在AngularJS和Testacular中测试广播前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用拦截401响应的 angular-http-auth模块.此模块广播事件:auth-loginrequired如果有一个401响应,可以使用$on()接收.但是我怎么测试呢?

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

解决方法

根据你的评论,我认为你不需要任何期望($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','');

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

猜你在找的Angularjs相关文章