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

angularjs – 如何在指令中对$emit进行单元测试?

发布时间:2020-12-17 17:20:22 所属栏目:安全 来源:网络整理
导读:如何在指令的单元测试中检查是否已调用$emit? 我的指令相当简单(为了说明的目的): angular.module('plunker',[]).directive('uiList',[function () { return { scope: { lengthModel: '=uiList',},link: function (scope,elm,attrs) { scope.$watch('lengt
如何在指令的单元测试中检查是否已调用$emit?

我的指令相当简单(为了说明的目的):

angular.module('plunker',[])
.directive('uiList',[function () { 
    return {
        scope: {
            lengthModel: '=uiList',},link: function (scope,elm,attrs) {
            scope.$watch('lengthModel',function (newVal) {
                        scope.$emit('yolo');
            });
        }
    }
}])

所以每次属性uiList改变时,它都会发出事件.

我的单元测试代码如下:

describe('Testing $emit in directive',function() {
  var scope;
  var element;


  //you need to indicate your module in a test
    beforeEach(function () {
        module('plunker');
        inject(function ($rootScope,$compile) {
            scope = $rootScope.$new();
            scope.row= 1;
            spyOn(scope,'$emit');
        element = angular.element('<ul id="rows" ui-list="row">');
        $compile(element)(scope);
        });
    });

  it('should emit',function() {

    scope.$digest();
    scope.row = 2;
    scope.$digest();
    expect(scope.$emit).toHaveBeenCalledWith("yolo");
  });
});

这总是会让我错误地说明范围.$emit从未被调用过.
范围有问题吗?有人可以帮忙吗?

Plunker:http://plnkr.co/edit/AqhPwp?p=preview

解决方法

你的指令创建一个隔离的范围,它调用$emit,所以你需要监视这个;)

describe('Testing $emit in directive',function() {
  var scope;
  var element;
  var elementScope;

  beforeEach(module('plunker'));

  beforeEach(inject(function($rootScope,$compile) {
      scope = $rootScope.$new();
      scope.row = 1;
      element = angular.element('<ul id="rows" ui-list="row">');
      $compile(element)(scope);
      scope.$digest();
      elementScope = element.scope();
  }));

  it('should emit',function() {
    // arrange
    spyOn(elementScope,'$emit');

    // act
    scope.$apply(function() {
      scope.row = 2;
    });

    // assert
    expect(elementScope.$emit).toHaveBeenCalledWith("yolo");
  });
});

Fixed plunker here

(编辑:李大同)

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

    推荐文章
      热点阅读