单元测试angularjs指令监听事件

Unit testing angularjs directive listening to an event

本文关键字:事件 监听 指令 angularjs 单元测试      更新时间:2023-09-26

我创建了一个监听事件并更新其内容的指令,如下所示:

$rootScope.$on(event, function(e, msg) {
  vm.items = msg.data;
});

我想为此创建一个单元测试,我知道如何测试指令是否广播,但我不知道如何测试指令是否在监听。

下面是我如何测试指令是否在监听:
describe('input directive', function() {
  var ctrl,
      $rootScope;
  beforeEach(function() {
    module('hey.ui');
    inject(function($compile, _$rootScope_) {
      $rootScope = _$rootScope_;
      var elem = $compile('<m-search></m-search>')($rootScope.$new());
      $rootScope.$digest();
      ctrl = elem.controller('mSearch');
      spyOn($rootScope, '$broadcast');
    })
  });
  it('broadcasts e:input-valuechanged on change', function() {
    var inputVal = {input: 'input string'};
    ctrl.onChange(inputVal);
    expect($rootScope.$broadcast).toHaveBeenCalledWith('e:input-valuechanged', {data: inputVal});
  });
});

我在想一个非常愚蠢的测试方法,像这样:

describe('list directive', function() {
  var ctrl,
      $rootScope;
  beforeEach(function() {
    module('hey.ui');
    inject(function($compile, _$rootScope_) {
      $rootScope = _$rootScope_;
      var elem = $compile('<ecal-list></ecal-list>')($rootScope.$new());
      $rootScope.$digest();
      ctrl = elem.controller('mList');
      spyOn($rootScope, '$broadcast');
    })
  });
  it('should listen to $broadcast', function() {
    $rootScope.$broadcast('e:input-valuechanged');
    var eventEmitted = false;
    $rootScope.$on('e:input-valuechanged', function() {
       eventEmitted = true;
       console.log(eventEmitted);
    });
    //run code to test
    expect(eventEmitted).toBe(true);
  });
});

如何测试一个指令是否正在监听一个特定的事件?

我相信你想在广播前收听e:input-valuechanged事件;

it('should listen to $broadcast', function() {
  var eventEmitted = false;
  $rootScope.$on('e:input-valuechanged', function() {
    eventEmitted = true;
    console.log(eventEmitted);
  });
  $rootScope.$broadcast('e:input-valuechanged');
  //run code to test
  expect(eventEmitted).toBe(true);
});