在 AngularJS 和 Testacular 中测试广播

标签 testing angularjs jasmine karma-runner

我正在使用 angular-http-auth拦截 401 响应的模块。如果有可以用 $on() 接收的 401 响应,此模块将广播 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();
  });
});

最佳答案

根据您的评论,我认为您不需要任何 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();        
    });
});

关于在 AngularJS 和 Testacular 中测试广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15410074/

相关文章:

ios - 使 Pod 仅可用于测试,不可用于源

node.js - 如何避免 jasmine 在不同环境下出现较长的相对路径(../../../)?

javascript - 带有 Angular 的书芯 JS

unit-testing - Angular 2.0.1 创建了一个具有不同配置的平台。请先销毁它

javascript - 预期 [false] 为 false Protractor e2e 测试失败

perl - 如何一次在xt中运行测试?

javascript - 无法使 CORS 请求正常工作

javascript - 需要使用双向绑定(bind)的 Angular 2 升级的工作示例

angularjs - 使用 Jasmine 测试一个简单的 AngularJS 服务

testing - Web 应用程序中导入 excel 功能的测试用例场景?