From 4e65ff31a8c4740752a636e2e1649d0427a1a154 Mon Sep 17 00:00:00 2001 From: Timothy Ahong Date: Tue, 23 Apr 2013 13:00:05 +0100 Subject: docs(guide:unit-testing): add an example unit test for directives --- docs/content/guide/dev_guide.unit-testing.ngdoc | 57 ++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) (limited to 'docs/content/guide/dev_guide.unit-testing.ngdoc') diff --git a/docs/content/guide/dev_guide.unit-testing.ngdoc b/docs/content/guide/dev_guide.unit-testing.ngdoc index 27f91ef6..73334af7 100644 --- a/docs/content/guide/dev_guide.unit-testing.ngdoc +++ b/docs/content/guide/dev_guide.unit-testing.ngdoc @@ -275,7 +275,62 @@ expect(length('abc')).toEqual(3); ## Directives -Directives in angular are responsible for updating the DOM when the state of the model changes. +Directives in angular are responsible for encapsulating complex functionality within custom HTML tags, +attributes, classes or comments. Unit tests are very important for directives because the components +you create with directives may be used throughout your application and in many different contexts. + +### Simple HTML Element Directive + +Lets start with an angular app with no dependencies. + +
+var app = angular.module('myApp', []);
+
+
+Now we can add a directive to our app.
+
+
+app.directive('aGreatEye', function () {
+ return {
+ restrict: 'E',
+ replace: true,
+ template: 'lidless, wreathed in flame
'
+ };
+});
+
+
+This directive is used as a tag `
+describe('Unit testing great quotes', function() {
+ var $compile;
+ var $rootScope;
+
+ // Load the myApp module, which contains the directive
+ beforeEach(module('myApp'));
+
+ // Store references to $rootScope and $compile
+ // so they are available to all tests in this describe block
+ beforeEach(inject(function(_$compile_, _$rootScope_){
+ // The injector unwraps the underscores (_) from around the parameter names when matching
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ }));
+
+ it('Replaces the element with the appropriate content', function() {
+ // Compile a piece of HTML containing the directive
+ var element = $compile(" ")($rootScope);
+ // Check that the compiled element contains the templated content
+ expect(element.html()).toContain("lidless, wreathed in flame");
+ });
+});
+
+
+We inject the $compile service and $rootScope before each jasmine test. The $compile service is used
+to render the aGreatEye directive. After rendering the directive we ensure that the directive has
+replaced the content and "lidless, wreathed in flame" is present.
## Mocks
oue
--
cgit v1.2.3