Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a key press event in angular directive

I've created an edit directive to wrap an html input in a fancy frame.

Now I'm creating a unit test to check that once I type in the input the dirty state of the form controller is set. This is what I got so far but it fails on the 2nd expect.

What's wrong here?

Thanks in advance!

describe('dirty', function () {
    it('false', function () {
        var scope = $rootScope.$new(),
            form = $compile('<form name="form"><edit ng-model="model"></edit></form>')(scope),
            input = form.find('input');
        scope.$digest();
        expect(scope.form.$dirty).toBeFalsy();
        input.triggerHandler('keydown', { which: 65 });
        expect(scope.form.$dirty).toBeTruthy();
    });
});

Edit:

For all that matters it comes down to this plunker (no jQuery) ... or this one using jQuery

Any idea?

like image 823
spacemigas Avatar asked May 08 '14 20:05

spacemigas


1 Answers

The angular unit tests in ngKeySpec.js were helpful:

it('should get called on a keydown', inject(function($rootScope, $compile) {
    element = $compile('<input ng-keydown="touched = true">')($rootScope);
    $rootScope.$digest();
    expect($rootScope.touched).toBeFalsy();

    browserTrigger(element, 'keydown');
    expect($rootScope.touched).toEqual(true);
  }));
like image 159
aet Avatar answered Oct 14 '22 20:10

aet