Mastering Web Application

(Rick Simeone) #1
Chapter 8

The advantage of this is that we do not have to rely on the widget's interface being
documented accurately. By calling the actual methods and checking that the user
interface is updated correctly, we can be very sure that our directive is working.
The disadvantages are that the DOM manipulation in the widget can slow down
the test runs and there must be a way to interact with the widget to ensure that it is
behaving correctly.


In this case, the jQueryUI datepicker widget exposes another function that allows
us to simulate a user selecting a date:


$.datepicker._selectDate(element);

We create a helper function selectDate(), which we will use to simulate date
selection on the widget:


var selectDate = function(element, date) {
element.datepicker('setDate', date);
$.datepicker._selectDate(element);
};

This kind of simulation is sometimes hard to achieve, and if so, you
should consider mocking out the widget altogether.

The tests themselves make use of the widget's API and this helper function.
For example:


describe('simple use on input element', function() {
var aDate, element;
beforeEach(function() {
aDate = new Date(2010, 12, 1);
element = $compile(
"<input date-picker ng-model='x'/>")($rootScope);
});
it('should get the date from the model', function() {
$rootScope.x = aDate;
$rootScope.$digest();
expect(element.datepicker('getDate')).toEqual(aDate);
});

it('should put the date in the model', function() {
$rootScope.$digest();
selectDate(element, aDate);
expect($rootScope.x).toEqual(aDate);
});
});
Free download pdf