Mastering Web Application

(Rick Simeone) #1

Building Your Own Directives


In our Admin User Form, we would like to check whether the e-mail address that
a user is entering has already been taken. We will create a uniqueEmail directive,
which will check with our back-end server to find if the e-mail address is already
in use:


<input ng-model="user.email" unique-email>

Mocking up the Users service


We use the Users resource service to query the database for the e-mail addresses
that are already in use. We need to mock up the query() method in this service
for our test.


In this case, it is easiest to create a test module and mock out a
Users service object instead of injecting the service and spying
on the query() method since the Users service itself relies on a
number of other services and constants.

angular.module('mock.Users', []).factory('Users', function() {
var Users = { };
Users.query = function(query, response) {
Users.respondWith = function(emails) {
response(emails);
Users.respondWith = undefined;
};
};
return Users;
});

The query() function creates Users.respondWith() that will call the response
callback that was passed to query(). This allows us to simulate a response to the
query in our tests.


Before Users.query() has been called and after it has been
handled with a call to Users.respondWith(), we set the
Users.respondWith function to undefined.

We then load this module in addition to the module under test:


beforeEach(module('mock.users'));

This causes the original Users service to be overridden by our mock service.

Free download pdf