加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在AngularJS和Testacular中测试广播

发布时间:2020-12-17 17:52:40 所属栏目:安全 来源:网络整理
导读:我正在使用拦截401响应的 angular-http-auth模块.此模块广播事件:auth-loginRequired如果有一个401响应,可以使用$on()接收.但是我怎么测试呢? beforeEach(inject(function($injector,$rootScope) { $httpBackend = $injector.get('$httpBackend'); myApi =
我正在使用拦截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();        
    });
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读