How to test AngularJS directives

后端 未结 2 496
谎友^
谎友^ 2021-01-29 22:43

I am working on a Rails 3.2 app that will be using AngularJS. I can get Angular to do what I need, but I am having a very difficult time figuring out how to test what I\'m doing

相关标签:
2条回答
  • 2021-01-29 23:23

    Angular Test Patterns may help you, there are examples in both coffeescript and javascript.

    Here's a testing pattern to verify the example directive is rendering the expected output.

    0 讨论(0)
  • 2021-01-29 23:34

    Here's how alert directive is tested in angular-ui/bootstrap.

    Here's another simple set of tests, for the buttons directive.

    Here are a few tips:

    • Be sure to tell the test runner what module you are testing with beforeEach(module('myModule')).

    • If you have external templateUrls in your directives, you'll want to somehow pre-cache them for the test runner. The test runner can't asynchronously GET templates. In bootstrap, we inject the templates into the javascript with a build step, and make each template a module. We use grunt-html2js grunt task.

    • In your tests, use the inject helper in a beforeEach to inject $compile and $rootScope and any other services you'll need. Use var myScope = $rootScope.$new() to create a fresh scope for each test. You can do var myElement = $compile('<my-directive></my-directive>')(myScope); to create an instance of your directive, and have access to its element.

    • If a directive creates its own scope and you want to test against it, you can get access to that directive's scope by doing var directiveScope = myElement.children().scope() - It will get the element's child (the directive itself), and get the scope for that.

    • For testing timeouts, you can use $timeout.flush() to end all pending timeouts.

    • For testing promises, remember that when you resolve a promise, it will not call its then callbacks until the next digest. So in tests you have to do this a lot: deferred.resolve(); scope.$apply();.

    You can find tests for directives of varying complexity in the bootstrap repo. Just look in src/{directiveName}/test/.

    0 讨论(0)
提交回复
热议问题