Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 0ce7034

Browse files
committed
docs(unit testing): improve unit testing guide
This commit adds to the unit testing guide: - add explicit section on additional libraries: Karma, Jasmine and angular-mocks and link to the docs for those projects too. Explain the benefit and use case for each of these libaries - Add more fully featured test examples and add more documentation around them, in particular the controller test - more clearly distinguish between the section on principles of testing and actual tutorial on writing a test This should close #8220.
1 parent 5c43b94 commit 0ce7034

File tree

1 file changed

+228
-99
lines changed

1 file changed

+228
-99
lines changed

docs/content/guide/unit-testing.ngdoc

+228-99
Original file line numberDiff line numberDiff line change
@@ -8,28 +8,26 @@ comes with almost no help from the compiler. For this reason we feel very strong
88
written in JavaScript needs to come with a strong set of tests. We have built many features into
99
Angular which makes testing your Angular applications easy. So there is no excuse for not testing.
1010

11-
# Separation of Concerns
11+
## Separation of Concerns
1212

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
1414
answer questions such as "Did I think about the logic correctly?" or "Does the sort function order
1515
the list in the right order?"
1616

1717
In order to answer such a question it is very important that we can isolate the unit of code under test.
1818
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.
2020

2121
While this may seem obvious it can be very difficult to call an individual function on a
2222
typical project. The reason is that the developers often mix concerns resulting in a
2323
piece of code which does everything. It makes an XHR request, it sorts the response data and then it
2424
manipulates the DOM.
2525

2626
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.
3331

3432
## With great power comes great responsibility
3533

@@ -182,86 +180,210 @@ Notice that no global variables were harmed in the writing of this test.
182180
Angular comes with {@link di dependency injection} built-in, making the right thing
183181
easy to do, but you still need to do it if you wish to take advantage of the testability story.
184182

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 tools for testing Angular applications
184+
185+
For testing Angular applications there are certain tools 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/1.3/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:
189207

190208
```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+
});
213212
```
214213

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:
217215

218216
```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+
});
230222
```
231223

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+
Grouping related tests within `describe` blocks and describing each individual test within an
225+
`it` call keeps your tests self documenting.
226+
227+
Finally, Jasmine provides matchers which let you make assertions:
234228

235229
```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-
}
230+
describe('sorting the list of users', function() {
231+
it('sorts in descending order by default', function() {
232+
var users = ['jack', 'igor', 'jeff'];
233+
var sorted = sortUsers(users);
234+
expect(sorted).toEqual(['jeff', 'jack', 'igor']);
235+
});
236+
});
249237
```
250238

251-
and the test is straight forward:
239+
Jasmine comes with a number of matchers that help you make a variety of assertions. You should [read
240+
the Jasmine documentation](http://jasmine.github.io/1.3/introduction.html#section-Matchers) to see
241+
what they are. To use Jasmine with Karma, we use the
242+
[karma-jasmine](https://github.com/karma-runner/karma-jasmine) test runner.
243+
244+
### angular-mocks
245+
246+
Angular also provides the {@link ngMock} module, which provides mocking for your tests. This is used
247+
to inject and mock Angular services within unit tests. In addition, it is able to extend other
248+
modules so they are synchronous. Having tests synchronous keeps them much cleaner and easier to work
249+
with. One of the most useful parts of ngMock is {@link ngMock.$httpBackend}, which lets us mock XHR
250+
requests in tests, and return sample data instead.
251+
252+
## Testing a Controller
253+
254+
Because Angular separates logic from the view layer, it keeps controllers easy to test. Let's take a
255+
look at how we might test the controller below, which provides `$scope.grade`, which sets a property
256+
on the scope based on the length of the password.
252257

253258
```js
254-
var $scope = {};
255-
var pc = $controller('PasswordCtrl', { $scope: $scope });
256-
$scope.password = 'abc';
257-
$scope.grade();
258-
expect($scope.strength).toEqual('weak');
259+
angular.module('app', [])
260+
.controller('PasswordController', function PasswordController($scope) {
261+
$scope.password = '';
262+
$scope.grade = function() {
263+
var size = $scope.password.length;
264+
if (size > 8) {
265+
$scope.strength = 'strong';
266+
} else if (size > 3) {
267+
$scope.strength = 'medium';
268+
} else {
269+
$scope.strength = 'weak';
270+
}
271+
};
272+
});
259273
```
260274

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.
275+
Because controllers are not available on the global scope, we need to use {@link
276+
angular.mock.inject} to inject our controller first. The first step is to use the `module` function,
277+
which is provided by angular-mocks. This loads in the module it's given, so it is available in your
278+
tests. We pass this into `beforeEach`, which is a function Jasmine provides that lets us run code
279+
before each test. Then we can use `inject` to access `$controller`, the service that is responsible
280+
for instantiating controllers.
263281

264-
## Filters
282+
```js
283+
describe('PasswordController', function() {
284+
beforeEach(module('app'));
285+
286+
var $controller;
287+
288+
beforeEach(inject(function(_$controller_){
289+
// The injector unwraps the underscores (_) from around the parameter names when matching
290+
$controller = _$controller_;
291+
}));
292+
293+
describe('$scope.grade', function() {
294+
it('sets the strength to "strong" if the password length is >8 chars', function() {
295+
var $scope = {};
296+
var controller = $controller('PasswordController', { $scope: $scope });
297+
$scope.password = 'longerthaneightchars';
298+
$scope.grade();
299+
expect($scope.strength).toEqual('strong');
300+
});
301+
});
302+
});
303+
```
304+
305+
Notice how by nesting the `describe` calls and being descriptive when calling them with strings, the
306+
test is very clear. It documents exactly what it is testing, and at a glance you can quickly see
307+
what is happening. Now let's add the test for when the password is less than three characters, which
308+
should see `$scope.strength` set to "weak":
309+
310+
```js
311+
describe('PasswordController', function() {
312+
beforeEach(module('app'));
313+
314+
var $controller;
315+
316+
beforeEach(inject(function(_$controller_){
317+
// The injector unwraps the underscores (_) from around the parameter names when matching
318+
$controller = _$controller_;
319+
}));
320+
321+
describe('$scope.grade', function() {
322+
it('sets the strength to "strong" if the password length is >8 chars', function() {
323+
var $scope = {};
324+
var controller = $controller('PasswordController', { $scope: $scope });
325+
$scope.password = 'longerthaneightchars';
326+
$scope.grade();
327+
expect($scope.strength).toEqual('strong');
328+
});
329+
330+
it('sets the strength to "weak" if the password length <3 chars', function() {
331+
var $scope = {};
332+
var controller = $controller('PasswordController', { $scope: $scope });
333+
$scope.password = 'a';
334+
$scope.grade();
335+
expect($scope.strength).toEqual('weak');
336+
});
337+
});
338+
});
339+
```
340+
341+
Now we have two tests, but notice the duplication between the tests. Both have to
342+
create the `$scope` variable and create the controller. As we add new tests, this duplication is
343+
only going to get worse. Thankfully, Jasmine provides `beforeEach`, which lets us run a function
344+
before each individual test. Let's see how that would tidy up our tests:
345+
346+
```js
347+
describe('PasswordController', function() {
348+
beforeEach(module('app'));
349+
350+
var $controller;
351+
352+
beforeEach(inject(function(_$controller_){
353+
// The injector unwraps the underscores (_) from around the parameter names when matching
354+
$controller = _$controller_;
355+
}));
356+
357+
describe('$scope.grade', function() {
358+
var $scope, controller;
359+
360+
beforeEach(function() {
361+
$scope = {};
362+
controller = $controller('PasswordController', { $scope: $scope });
363+
});
364+
365+
it('sets the strength to "strong" if the password length is >8 chars', function() {
366+
$scope.password = 'longerthaneightchars';
367+
$scope.grade();
368+
expect($scope.strength).toEqual('strong');
369+
});
370+
371+
it('sets the strength to "weak" if the password length <3 chars', function() {
372+
$scope.password = 'a';
373+
$scope.grade();
374+
expect($scope.strength).toEqual('weak');
375+
});
376+
});
377+
});
378+
```
379+
380+
We've moved the duplication out and into the `beforeEach` block. Each individual test now
381+
only contains the code specific to that test, and not code that is general across all tests. As you
382+
expand your tests, keep an eye out for locations where you can use `beforeEach` to tidy up tests.
383+
`beforeEach` isn't the only function of this sort that Jasmine provides, and the [documentation
384+
lists the others](http://jasmine.github.io/1.3/introduction.html#section-Setup_and_Teardown).
385+
386+
## Testing Filters
265387
{@link ng.$filterProvider Filters} are functions which transform the data into a user readable
266388
format. They are important because they remove the formatting responsibility from the application
267389
logic, further simplifying the application logic.
@@ -273,12 +395,20 @@ myModule.filter('length', function() {
273395
}
274396
});
275397

276-
var length = $filter('length');
277-
expect(length(null)).toEqual(0);
278-
expect(length('abc')).toEqual(3);
398+
describe('length filter', function() {
399+
it('returns 0 when given null', function() {
400+
var length = $filter('length');
401+
expect(length(null)).toEqual(0);
402+
});
403+
404+
it('returns the correct value when given a string of chars', function() {
405+
var length = $filter('length');
406+
expect(length('abc')).toEqual(3);
407+
});
408+
});
279409
```
280410

281-
## Directives
411+
## Testing Directives
282412
Directives in angular are responsible for encapsulating complex functionality within custom HTML tags,
283413
attributes, classes or comments. Unit tests are very important for directives because the components
284414
you create with directives may be used throughout your application and in many different contexts.
@@ -309,28 +439,28 @@ verify this functionality. Note that the expression `{{1 + 1}}` times will also
309439

310440
```js
311441
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-
});
442+
var $compile,
443+
$rootScope;
444+
445+
// Load the myApp module, which contains the directive
446+
beforeEach(module('myApp'));
447+
448+
// Store references to $rootScope and $compile
449+
// so they are available to all tests in this describe block
450+
beforeEach(inject(function(_$compile_, _$rootScope_){
451+
// The injector unwraps the underscores (_) from around the parameter names when matching
452+
$compile = _$compile_;
453+
$rootScope = _$rootScope_;
454+
}));
455+
456+
it('Replaces the element with the appropriate content', function() {
457+
// Compile a piece of HTML containing the directive
458+
var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
459+
// fire all the watches, so the scope expression {{1 + 1}} will be evaluated
460+
$rootScope.$digest();
461+
// Check that the compiled element contains the templated content
462+
expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
463+
});
334464
});
335465
```
336466

@@ -431,4 +561,3 @@ Otherwise you may run into issues if the test directory hierarchy differs from t
431561

432562
## Sample project
433563
See the [angular-seed](https://github.com/angular/angular-seed) project for an example.
434-

0 commit comments

Comments
 (0)