单元测试 – 如何在角度单元测试中从指令而不是控制器模拟范围
发布时间:2020-12-17 17:31:03 所属栏目:安全 来源:网络整理
导读:所以我熟悉使用$controller构造函数模拟$scope和controller的概念 var scope = rootScope.$new();it('should contain a testVar value at "test var home"',function(){ homeCtrl = $controller('homeCtrl',{ $scope: homeScope,$rootScope: rootScope }) ex
所以我熟悉使用$controller构造函数模拟$scope和controller的概念
var scope = rootScope.$new(); it('should contain a testVar value at "test var home"',function(){ homeCtrl = $controller('homeCtrl',{ $scope: homeScope,$rootScope: rootScope }) expect(homeScope.testVar).toBe('test var home'); }) 有没有办法以同样的方式模拟指令?指令和它的控制器? //mock coding var scope = rootScope.$new(); it('should contain a testVar value at "test var home"',function(){ homeDir = $directive('homeCtrl',$elem: angular.element('<div....</div>'),$att: {} $modelViewController: angular.element().controller('ngModel') }) homeCtrl = homeDir.$getController(); expect(homeScope.testVar).toBe('test var home'); }) 这个问题意味着针对指令,如何测试它们?如何提取他们的组件?根据我所知道的,如果我在指令上有一个函数,我需要将它附加到一个作用域,否则如果它属于指令那么该函数是不可测试的.所以,如果我想在测试期间使用范围如何将范围注入变量? 解决方法
我设置指令规范的方法是
beforeEach(inject(function($rootScope,$compile) { var htmlString = '' + '<my-directive some-attr="value">' + '</my-directive>' ; element = angular.element(htmlString) scope = $rootScope.$new(); $compile(element)(scope); scope.$digest(); })); 基本上我编译了一个声明我的指令的HTML字符串,并使用我注入的范围运行结果函数.然后我使用JQuery(或JQueryLite)与元素交互或直接在作用域上执行断言 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |