角度事件侦听器未出现在测试中

Angular event listener not appearing in tests

本文关键字:测试 事件 侦听器      更新时间:2023-09-26

假设我有一个指令:

angular.module('foo').directive('myDir', function () {
  return {
    restrict: 'E',
    link: function (scope) {
      var watcher = scope.$watch('foo, function () {});
      scope.$on('$destroy', function () {
        watcher();
      });
    }
  }
})

然后进行以下测试:

describe('myDir', function () {
  beforeEach(function () {
    module('foo');
    inject(function($compile, $rootScope) {
      var scope = $rootScope.$new();
      $compile('<my-dir></my-dir>')(scope);
      scope.$digest();
    });
  });
  it('listens for destroy', function () {
    expect(scope.$$listeners.$destroy).to.not.equal(undefined);
  });
});

以下情况失败:Error: expected undefined to not equal undefined

奇怪的是,如果我在expect之前直接console.log(scope.$$listeners.$destroy),日志会显示一个函数数组,而不是未定义的,但测试仍然失败。

是什么导致侦听器对断言不可见?有好的变通办法吗?

.to.not.equal 更改

not.to.be

修复了的问题