@@ -275,7 +275,62 @@ expect(length('abc')).toEqual(3);
275
275
</pre>
276
276
277
277
## Directives
278
- Directives in angular are responsible for updating the DOM when the state of the model changes.
278
+ Directives in angular are responsible for encapsulating complex functionality within custom HTML tags,
279
+ attributes, classes or comments. Unit tests are very important for directives because the components
280
+ you create with directives may be used throughout your application and in many different contexts.
281
+
282
+ ### Simple HTML Element Directive
283
+
284
+ Lets start with an angular app with no dependencies.
285
+
286
+ <pre>
287
+ var app = angular.module('myApp', []);
288
+ </pre>
289
+
290
+ Now we can add a directive to our app.
291
+
292
+ <pre>
293
+ app.directive('aGreatEye', function () {
294
+ return {
295
+ restrict: 'E',
296
+ replace: true,
297
+ template: '<h1>lidless, wreathed in flame</h1>'
298
+ };
299
+ });
300
+ </pre>
301
+
302
+ This directive is used as a tag `<a-great-eye></a-great-eye>`. It replaces the entire tag with the
303
+ template `<h1>lidless, wreathed in flame</h1>`. Now we are going to write a jasmine unit test to
304
+ verify this functionality.
305
+
306
+ <pre>
307
+ describe('Unit testing great quotes', function() {
308
+ var $compile;
309
+ var $rootScope;
310
+
311
+ // Load the myApp module, which contains the directive
312
+ beforeEach(module('myApp'));
313
+
314
+ // Store references to $rootScope and $compile
315
+ // so they are available to all tests in this describe block
316
+ beforeEach(inject(function(_$compile_, _$rootScope_){
317
+ // The injector unwraps the underscores (_) from around the parameter names when matching
318
+ $compile = _$compile_;
319
+ $rootScope = _$rootScope_;
320
+ }));
321
+
322
+ it('Replaces the element with the appropriate content', function() {
323
+ // Compile a piece of HTML containing the directive
324
+ var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
325
+ // Check that the compiled element contains the templated content
326
+ expect(element.html()).toContain("lidless, wreathed in flame");
327
+ });
328
+ });
329
+ </pre>
330
+
331
+ We inject the $compile service and $rootScope before each jasmine test. The $compile service is used
332
+ to render the aGreatEye directive. After rendering the directive we ensure that the directive has
333
+ replaced the content and "lidless, wreathed in flame" is present.
279
334
280
335
## Mocks
281
336
oue
0 commit comments