@@ -8,28 +8,26 @@ comes with almost no help from the compiler. For this reason we feel very strong
8
8
written in JavaScript needs to come with a strong set of tests. We have built many features into
9
9
Angular which makes testing your Angular applications easy. So there is no excuse for not testing.
10
10
11
- # Separation of Concerns
11
+ ## Separation of Concerns
12
12
13
- Unit testing as the name implies is about testing individual units of code. Unit tests try to
13
+ Unit testing, as the name implies, is about testing individual units of code. Unit tests try to
14
14
answer questions such as "Did I think about the logic correctly?" or "Does the sort function order
15
15
the list in the right order?"
16
16
17
17
In order to answer such a question it is very important that we can isolate the unit of code under test.
18
18
That is because when we are testing the sort function we don't want to be forced into creating
19
- related pieces such as the DOM elements, or making any XHR calls in getting the data to sort.
19
+ related pieces such as the DOM elements, or making any XHR calls to fetch the data to sort.
20
20
21
21
While this may seem obvious it can be very difficult to call an individual function on a
22
22
typical project. The reason is that the developers often mix concerns resulting in a
23
23
piece of code which does everything. It makes an XHR request, it sorts the response data and then it
24
24
manipulates the DOM.
25
25
26
26
With Angular we try to make it easy for you to do the right thing, and so we
27
- provide dependency injection for your XHR (which you can mock out) and we created abstractions which
28
- allow you to sort your model without having to resort to manipulating the DOM. So that in the end,
29
- it is easy to write a sort function which sorts some data, so that your test can create a data set,
30
- apply the function, and assert that the resulting model is in the correct order. The test does not
31
- have to wait for the XHR response to arrive, create the right kind of test DOM, nor assert that your
32
- function has mutated the DOM in the right way.
27
+ provide dependency injection for your XHR requests, which can be mocked, and we provide abstractions which
28
+ allow you to test your model without having to resort to manipulating the DOM. The test can then
29
+ assert that the data has been sorted without having to create or look at the state of the DOM or
30
+ wait for any XHR requests to return data. The individual sort function can be tested in isolation.
33
31
34
32
## With great power comes great responsibility
35
33
@@ -182,86 +180,179 @@ Notice that no global variables were harmed in the writing of this test.
182
180
Angular comes with {@link di dependency injection} built-in, making the right thing
183
181
easy to do, but you still need to do it if you wish to take advantage of the testability story.
184
182
185
- ## Controllers
186
- What makes each application unique is its logic, and the logic is what we would like to test. If the logic
187
- for your application contains DOM manipulation, it will be hard to test. See the example
188
- below:
183
+ ## Additional libraries for testing Angular applications
184
+
185
+ For testing Angular applications there are libraries that you should use that will make testing much
186
+ easier to set up and run.
187
+
188
+ ### Karma
189
+
190
+ [Karma](http://karma-runner.github.io/) is a JavaScript command line tool that can be used to spawn
191
+ a web server which loads your application's source code and executes your tests. You can configure
192
+ Karma to run against a number of browsers, which is useful for being confident that your application
193
+ works on all browsers you need to support. Karma is executed on the command line and will display
194
+ the results of your tests on the command line once they have run in the browser.
195
+
196
+ Karma is a NodeJS application, and should be installed through npm. Full installation instructions
197
+ are available on [the Karma website](http://karma-runner.github.io/0.12/intro/installation.html).
198
+
199
+ ### Jasmine
200
+
201
+ [Jasmine](http://jasmine.github.io/2.0/introduction.html) is a test driven development framework for
202
+ JavaScript that has become the most popular choice for testing Angular applications. Jasmine
203
+ provides functions to help with structuring your tests and also making assertions. As your tests
204
+ grow, keeping them well structured and documented is vital, and Jasmine helps achieve this.
205
+
206
+ In Jasmine we use the `describe` function to group our tests together:
189
207
190
208
```js
191
- function PasswordCtrl() {
192
- // get references to DOM elements
193
- var msg = $('.ex1 span');
194
- var input = $('.ex1 input');
195
- var strength;
196
-
197
- this.grade = function() {
198
- msg.removeClass(strength);
199
- var pwd = input.val();
200
- password.text(pwd);
201
- if (pwd.length > 8) {
202
- strength = 'strong';
203
- } else if (pwd.length > 3) {
204
- strength = 'medium';
205
- } else {
206
- strength = 'weak';
207
- }
208
- msg
209
- .addClass(strength)
210
- .text(strength);
211
- }
212
- }
209
+ describe("sorting the list of users", function() {
210
+ // individual tests go here
211
+ });
213
212
```
214
213
215
- The code above is problematic from a testability point of view since it requires your test to have the right kind
216
- of DOM present when the code executes. The test would look like this:
214
+ And then each individual test is defined within a call to the `it` function:
217
215
218
216
```js
219
- var input = $('<input type="text"/>');
220
- var span = $('<span>');
221
- $('body').html('<div class="ex1">')
222
- .find('div')
223
- .append(input)
224
- .append(span);
225
- var pc = new PasswordCtrl();
226
- input.val('abc');
227
- pc.grade();
228
- expect(span.text()).toEqual('weak');
229
- $('body').empty();
217
+ describe("sorting the list of users", function() {
218
+ it("sorts in descending order by default", function() {
219
+ // your test assertion goes here
220
+ });
221
+ });
230
222
```
231
223
232
- In angular the controllers are strictly separated from the DOM manipulation logic and this results in
233
- a much easier testability story as the following example shows:
224
+ By grouping related tests within `describe` blocks, and describing each individual test within an
225
+ `it` call, this keeps your tests self documented. Finally, Jasmine provides matchers which let you
226
+ make assertions:
234
227
235
228
```js
236
- function PasswordCtrl($scope) {
237
- $scope.password = '';
238
- $scope.grade = function() {
239
- var size = $scope.password.length;
240
- if (size > 8) {
241
- $scope.strength = 'strong';
242
- } else if (size > 3) {
243
- $scope.strength = 'medium';
244
- } else {
245
- $scope.strength = 'weak';
246
- }
247
- };
248
- }
229
+ describe("sorting the list of users", function() {
230
+ it("sorts in descending order by default", function() {
231
+ var users = ['jack', 'igor', 'jeff'];
232
+ var sorted = sortUsers(users);
233
+ expect(sorted).toEqual(['jeff', 'jack', 'igor']);
234
+ });
235
+ });
236
+ ```
237
+
238
+ Jasmine comes with a number of matchers that help you make a variety of assertions. You should [read
239
+ the Jasmine documentation](http://jasmine.github.io/2.0/introduction.html#section-Matchers) to see
240
+ what they are.
241
+
242
+ ### angular-mocks
243
+
244
+ Angular also provides the {@link ngMock} module, which provides mocking for your tests. This is used
245
+ to inject and mock Angular services within unit tests. In addition, it is able to extend other
246
+ modules so they are synchronous. Having tests synchronous keeps them much cleaner and easier to work
247
+ with. One of the most useful parts of ngMock is {@link ngMock.$httpBackend}, which lets us mock XHR
248
+ requests in tests, and return sample data instead.
249
+
250
+ ## Testing a Controller
251
+
252
+ Because Angular separates logic from the view layer, it keeps controllers easy to test. Let's take a
253
+ look at how we might test the controller below, which provides `$scope.grade`, which sets a property
254
+ on the scope based on the length of the password.
255
+
256
+ ```js
257
+ angular
258
+ .module('app')
259
+ .controller('PasswordController', function PasswordController($scope) {
260
+ $scope.password = '';
261
+ $scope.grade = function() {
262
+ var size = $scope.password.length;
263
+ if (size > 8) {
264
+ $scope.strength = 'strong';
265
+ } else if (size > 3) {
266
+ $scope.strength = 'medium';
267
+ } else {
268
+ $scope.strength = 'weak';
269
+ }
270
+ };
271
+ });
249
272
```
250
273
251
- and the test is straight forward:
274
+ The test below assumes that you have your controllers available on the global scope. If this isn't
275
+ the case, you can use {@link angular.mock.inject} to inject the controller into the test. We can use
276
+ Jasmine to structure our test:
252
277
253
278
```js
254
- var $scope = {};
255
- var pc = $controller('PasswordCtrl', { $scope: $scope });
256
- $scope.password = 'abc';
257
- $scope.grade();
258
- expect($scope.strength).toEqual('weak');
279
+ describe('PasswordController', function() {
280
+ describe('$scope.grade', function() {
281
+ it('sets the strength to "strong" if the password length is >8 chars', function() {
282
+ var $scope = {};
283
+ var ctrl = $controller('PasswordController', { $scope: $scope });
284
+ $scope.password = 'longerthaneightchars';
285
+ $scope.grade();
286
+ expect($scope.strength).toEqual('strong');
287
+ });
288
+ });
289
+ });
259
290
```
260
291
261
- Notice that the test is not only much shorter, it is also easier to follow what is happening. We say
262
- that such a test tells a story, rather than asserting random bits which don't seem to be related.
292
+ Notice how by nesting the `describe` calls and being descriptive when calling them with strings, the
293
+ test is very clear. It documents exactly what it is testing, and at a glance you can quickly see
294
+ what is happening. Now let's add the test for when the password is less than three characters, which
295
+ should see `$scope.strength` set to "weak":
263
296
264
- ## Filters
297
+ ```js
298
+ describe('PasswordController', function() {
299
+ describe('$scope.grade', function() {
300
+ it('sets the strength to "strong" if the password length is >8 chars', function() {
301
+ var $scope = {};
302
+ var ctrl = $controller('PasswordController', { $scope: $scope });
303
+ $scope.password = 'longerthaneightchars';
304
+ $scope.grade();
305
+ expect($scope.strength).toEqual('strong');
306
+ });
307
+
308
+ it('sets the strength to "weak" if the password length <3 chars', function() {
309
+ var $scope = {};
310
+ var ctrl = $controller('PasswordController', { $scope: $scope });
311
+ $scope.password = 'a';
312
+ $scope.grade();
313
+ expect($scope.strength).toEqual('weak');
314
+ });
315
+ });
316
+ });
317
+ ```
318
+
319
+ Now we have two tests, but notice the duplication between the tests. Both have to
320
+ create the `$scope` variable and create the controller. As we add new tests, this duplication is
321
+ only going to get worse. Thankfully, Jasmine provides `beforeEach`, which lets us run a function
322
+ before each individual test. Let's see how that would tidy up our tests:
323
+
324
+ ```js
325
+ describe('PasswordController', function() {
326
+ describe('$scope.grade', function() {
327
+ var $scope, ctrl;
328
+
329
+ beforeEach(function() {
330
+ $scope = {};
331
+ ctrl = $controller('PasswordController', { $scope: $scope });
332
+ });
333
+
334
+ it('sets the strength to "strong" if the password length is >8 chars', function() {
335
+ $scope.password = 'longerthaneightchars';
336
+ $scope.grade();
337
+ expect($scope.strength).toEqual('strong');
338
+ });
339
+
340
+ it('sets the strength to "weak" if the password length <3 chars', function() {
341
+ $scope.password = 'a';
342
+ $scope.grade();
343
+ expect($scope.strength).toEqual('weak');
344
+ });
345
+ });
346
+ });
347
+ ```
348
+
349
+ The duplication is now gone, and encapsulated within the `beforeEach`. Each individual test now only
350
+ contains the code specific to that test, and not code that is general across all tests. As you
351
+ expand your tests, keep an eye out for locations where you can use `beforeEach` to tidy up tests.
352
+ `beforeEach` isn't the only function of this sort that Jasmine provides, and the [documentation
353
+ lists the others](http://jasmine.github.io/2.0/introduction.html#section-Setup_and_Teardown).
354
+
355
+ ## Testing Filters
265
356
{@link ng.$filterProvider Filters} are functions which transform the data into a user readable
266
357
format. They are important because they remove the formatting responsibility from the application
267
358
logic, further simplifying the application logic.
@@ -273,12 +364,20 @@ myModule.filter('length', function() {
273
364
}
274
365
});
275
366
276
- var length = $filter('length');
277
- expect(length(null)).toEqual(0);
278
- expect(length('abc')).toEqual(3);
367
+ describe('length filter', function() {
368
+ it('returns 0 when given null', function() {
369
+ var length = $filter('length');
370
+ expect(length(null)).toEqual(0);
371
+ });
372
+
373
+ it('returns the correct value when given a string of chars', function() {
374
+ var length = $filter('length');
375
+ expect(length('abc')).toEqual(3);
376
+ });
377
+ });
279
378
```
280
379
281
- ## Directives
380
+ ## Testing Directives
282
381
Directives in angular are responsible for encapsulating complex functionality within custom HTML tags,
283
382
attributes, classes or comments. Unit tests are very important for directives because the components
284
383
you create with directives may be used throughout your application and in many different contexts.
@@ -309,28 +408,28 @@ verify this functionality. Note that the expression `{{1 + 1}}` times will also
309
408
310
409
```js
311
410
describe('Unit testing great quotes', function() {
312
- var $compile;
313
- var $rootScope;
314
-
315
- // Load the myApp module, which contains the directive
316
- beforeEach(module('myApp'));
317
-
318
- // Store references to $rootScope and $compile
319
- // so they are available to all tests in this describe block
320
- beforeEach(inject(function(_$compile_, _$rootScope_){
321
- // The injector unwraps the underscores (_) from around the parameter names when matching
322
- $compile = _$compile_;
323
- $rootScope = _$rootScope_;
324
- }));
325
-
326
- it('Replaces the element with the appropriate content', function() {
327
- // Compile a piece of HTML containing the directive
328
- var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
329
- // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
330
- $rootScope.$digest();
331
- // Check that the compiled element contains the templated content
332
- expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
333
- });
411
+ var $compile;
412
+ var $rootScope;
413
+
414
+ // Load the myApp module, which contains the directive
415
+ beforeEach(module('myApp'));
416
+
417
+ // Store references to $rootScope and $compile
418
+ // so they are available to all tests in this describe block
419
+ beforeEach(inject(function(_$compile_, _$rootScope_){
420
+ // The injector unwraps the underscores (_) from around the parameter names when matching
421
+ $compile = _$compile_;
422
+ $rootScope = _$rootScope_;
423
+ }));
424
+
425
+ it('Replaces the element with the appropriate content', function() {
426
+ // Compile a piece of HTML containing the directive
427
+ var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
428
+ // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
429
+ $rootScope.$digest();
430
+ // Check that the compiled element contains the templated content
431
+ expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
432
+ });
334
433
});
335
434
```
336
435
@@ -431,4 +530,3 @@ Otherwise you may run into issues if the test directory hierarchy differs from t
431
530
432
531
## Sample project
433
532
See the [angular-seed](https://github.com/angular/angular-seed) project for an example.
434
-
0 commit comments