Building and Testing
beforeEach(inject(function (_notificationsArchive_) {
notificationsArchive = _notificationsArchive_;
}));
it('should give access to the archived items', function () {
var notification = {msg: 'Old message.'};
notificationsArchive.archive(notification);
expect(notificationsArchive.getArchived())
.toContain(notification);
});
});
At this point you should be able to recognize the familiar structure of the Jasmine
test plus spot some new function calls: module and inject.
The module function is used in Jasmine tests to indicate that services from a given
module should be prepared for the test. The role of this method is similar to the
one played by the ng-app directive. It indicated that AngularJS $injector should
be created for a given module (and all the dependent modules).
Don't confuse the module function used in the test with the
angular.module method. While both have the same name
their roles are quite different. The angular.module method is
used to declare new modules while the module function allows
us to specify modules to be used in a test.
In reality it is possible to have multiple module function calls in one test. In this case
all the services, values and constants from the specified modules will be available
through the $injector.
The inject function has one simple responsibility, that is it injects the services into
our tests.
The last part that might be confusing is the presence of the mysterious underscores
in the inject function call:
var notificationsArchive;
beforeEach(inject(function (_notificationsArchive_) {
notificationsArchive = _notificationsArchive_;
}));
What is happening here is that $injector will strip any a pair leading and trailing
underscores when inspecting the function's arguments to retrieve dependencies.
This is a useful trick since we can save variable names without underscores for the
test itself.