我正在使用将使用AngularJS的Rails 3.2应用程序.我可以让Angular做我需要的东西,但是我很难搞清楚如何测试我正在做的事情.我正在使用guard-jasmine来使用PhantomJS运行Jasmine规范.
这是(相关)html:
<html id="ng-app" ng-app="app">
<div id="directive-element" class="directive-element">
</div>
</html>
Run Code Online (Sandbox Code Playgroud)
javascript(在coffeescript中)看起来像:
window.Project =
App: angular.module('app', [])
Directive: {}
Project.Directive.DirectiveElement =
->
restrict: 'C'
link: (scope, element, attrs) ->
element.html 'hello world'
Project.App.directive 'directiveElement', Project.Directive.DirectiveElement
Run Code Online (Sandbox Code Playgroud)
上面的代码完全符合它的目的.测试是问题所在.我根本无法让他们工作.这是我尝试过的一件事.发布这个主要是为了在某个地方开始对话.
describe 'App.Directive.DirectiveElement', ->
it 'updates directive-element', ->
inject ($compile, $rootScope) ->
element = $compile('<div id="app" ng-app="app"><div id="directive'element" class="directive-element"></div></div>')
expect(element.text()).toEqual('hello world')
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我是AngularJS的新手,所以如果有关于我没有遵循的命名空间,模块等的最佳实践,我们将非常感谢指导.
我如何进行测试才能使用?
我听说在使用隔离范围的指令中使用controllerAs语法是一个好习惯bindToController: true.参考文献:一,二
假设,我有这样的指令:
angular.module('MyModule').directive('MyDirective', function(User) {
return {
scope: {
name: '='
},
templateUrl: 'my-template.html',
link: function(scope) {
scope.User = User;
scope.doSomething = function() {
// Do something cool
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
<!-- my-template.html -->
<div>
User Id: {{ User.id }}
Name: {{ name }}
<button ng-click="doSomething()">Do it</button>
</div>
Run Code Online (Sandbox Code Playgroud)
如您所见,此指令中没有控制器.但是,为了能够利用controllerAs,bindToController: true我必须有一个控制器.
将链接功能转换为控制器是最佳做法吗?
angular.module('MyModule').directive('MyDirective', function(User) {
return {
scope: {
name: '='
},
templateUrl: 'my-template.html',
bindToController: true,
controllerAs: 'myCtrl', …Run Code Online (Sandbox Code Playgroud) 如果我有这样的指示
JS:
app.controller('MyController', function($scope) {
this.someMethod = function() {
};
});
app.directive('myDirective', function() {
return {
scope: true
link: function(scope, elem, attrs, controller) {
controller.someMethod();
}
controller: 'MyController',
}
});
Run Code Online (Sandbox Code Playgroud)
我想创建一个Jasmine间谍以确保调用链接函数controller.someMethod,但这不起作用:
规格:
var elem = angular.element('<div my-directive></div>');
var scope = $rootScope.new();
$compile(elem)(scope);
var ctrl = elem.controller('myDirective');
spyOn(ctrl, 'someFunc').andCallThrough();
Run Code Online (Sandbox Code Playgroud)
间谍创建得太晚,因为控制器已实例化并且$compile语句中调用了链接函数.
还有哪些方法可以监视链接功能中发生的事情?是否可以预先实例化控制器并将其传递给$compile?