sobota, 19 września 2015

How to touch input in AngularJS and Jasmine

describe("Touch a form input to make it display message", function() {
    it('Should display message when touched', inject(function($compile, $rootScope) {
        //given
        var compiledFormHtml = $compile(
            '<form name="testForm">\
                <input name="testEmail" type="email" ng-model="user.email"/> \
                <div ng-if="testForm.testEmail.$touched">\
                I am touched\
                </div>\
             </form>')
        ($rootScope);

        //when
        var input = compiledFormHtml.find('input');
        input.triggerHandler('blur');
        $rootScope.$digest();

        //then
        expect(compiledFormHtml.html()).toContain('I am touched')
    }));

    it('Should not display the message when not touched', inject(function($compile, $rootScope) {
        //given
        var compiledFormHtml = $compile(
            '<form name="testForm">\
                <input name="testEmail" type="email" ng-model="user.email"/> \
                <div ng-if="testForm.testEmail.$touched">\
                I am touched\
                </div>\
             </form>')
        ($rootScope);

        //when
        $rootScope.$digest();

        //then
        expect(compiledFormHtml.html()).not.toContain('I am touched')
    }));
});

Important things:

  • <form name="testForm"> name publishes the form's FormController into the scope. 
  • <input name="testEmail" type="email" ng-model="user.email"/> ng-model gives the input access to ngModelController, which again is published using the name attribute
  • compiledFormHtml is a JQLite object having a subset of JQuery methods. With find we get reference to the input, which again is a JQLite object. Then we call the blur event with the triggerHandler method, which makes the input actually touched.

Brak komentarzy:

Prześlij komentarz