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

angularjs – 如何在事件执行的控制器范围内测试函数

发布时间:2020-12-17 17:35:40 所属栏目:安全 来源:网络整理
导读:控制器中的功能: angular.module('myApp').controller('MyController',function(){ $scope.f = function($event){ $event.preventDefault(); //logic return data; }})describe('MyController',function(){ 'use strict'; var MyController,$scope; beforeE
控制器中的功能:

angular.module('myApp').controller('MyController',function(){

   $scope.f = function($event){
      $event.preventDefault();
      //logic
      return data;
   }
})

describe('MyController',function(){
    'use strict';
    var MyController,$scope;

    beforeEach(module('myApp'));

    beforeEach($inject(function($rootScope,$controller){
       $scope = $rootScope.$new();
       MyController = $controller('MyController',{
          $scope: $scope
       })
    }));
})
it('should...',function(){
    //fire event and expect data
})

$scope.f函数在指令中使用,可以通过ng-click =“f($event)”执行

在单元测试中火灾事件的正确方法是什么?

解决方法

简答

您无需触发该事件.您可以访问范围,该范围具有您要测试的功能.这意味着您只需执行该函数,然后断言.它看起来像这样:

it('should call preventDefault on the given event',function(){
  var testEvent = $.Event('someEvent');
  $scope.f(testEvent);
  expect(testEvent.isDefaultPrevented()).toBe(true);
});

请参阅以下内容:

> jQuery Event Object
> event.isDefaultPrevented()

完整规格

此外 – 您的it块应该在您的describe块中,以便它可以访问$scope字段.它应该看起来更像这样:

describe('MyController',function(){
  'use strict';
  var MyController,$scope;

  beforeEach(module('myApp'));

  beforeEach($inject(function($rootScope,$controller){
    $scope = $rootScope.$new();
    MyController = $controller('MyController',{
      $scope: $scope
    })
  }));

  it('should call preventDefault on the given event',function(){
    var testEvent = $.Event('someEvent');
    $scope.f(testEvent);
    expect(testEvent.isDefaultPrevented()).toBe(true);
  });
})

关于结构的一个注记

不要害怕使用describe块来构建测试.想象一下你在$scope上有另一个函数f2,那么你可能想要将你的spec文件分区更像这样:

describe('MyController',{
      $scope: $scope
    })
  }));

  describe('$scope',function() {
    describe('.f()',function() {
      // tests related to only the .f() function
    });

    describe('.f2()',function() {
      // tests related to only the .f2() function
    });
  });
})

这样做的好处是,当测试失败时,您看到的错误消息是基于describe块的层次结构构建的.所以它会是这样的:

MyController $scope .f() should call preventDefault on the given event

(编辑:李大同)

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

    推荐文章
      热点阅读