所以我熟悉使用$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)与元素交互或直接在作用域上执行断言