我正在开发一个将使用 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>
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
上面的代码完全按照预期的方式进行。测试是问题所在。我根本无法让他们工作。这是我试过的一件事。发布这个主要只是为了在某个地方开始对话。
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')
顺便说一句,我是 AngularJS 的新手,所以如果有任何我没有遵循的关于命名空间、模块等的最佳实践,将不胜感激。
如何进行测试以使其正常工作?
最佳答案
Here's how alert directive is tested in angular-ui/bootstrap .
Here's another simple set of tests, for the buttons directive.
这里有一些提示:
一定要告诉测试运行器你正在测试什么模块
beforeEach(module('myModule'))
.如果您的指令中有外部 templateUrls,您将希望以某种方式为测试运行器预缓存它们。测试运行器不能异步
GET
模板。在 Bootstrap 中,我们通过构建步骤将模板注入(inject)到 javascript 中,并使每个模板成为一个模块。我们使用grunt-html2js
咕噜任务。在您的测试中,使用
inject
beforeEach
中的 helper 注入(inject) $compile 和 $rootScope 以及您需要的任何其他服务。使用var myScope = $rootScope.$new()
为每个测试创建一个新的范围。你可以做var myElement = $compile('<my-directive></my-directive>')(myScope);
创建指令的实例,并可以访问其元素。如果一个指令创建了它自己的作用域,而您想针对它进行测试,您可以通过执行
var directiveScope = myElement.children().scope()
来访问该指令的作用域。 - 它将获取元素的子元素(指令本身),并获取该元素的范围。要测试超时,您可以使用
$timeout.flush()
结束所有未决超时。为了测试 promise,请记住,当您 resolve 一个 promise 时,它不会调用它的
then
回调直到下一个摘要。所以在测试中你必须经常这样做:deferred.resolve(); scope.$apply();
.
您可以在 the bootstrap repo 中找到针对不同复杂度的指令的测试。 .看看src/{directiveName}/test/
.
关于angularjs - 如何测试 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12755421/