6

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?

spacemigas
  • 791
  • 8
  • 10
  • Maybe you need to use keypress, or keyup instead? – aet May 08 '14 at 20:23
  • I've tried, but no luck :( – spacemigas May 08 '14 at 20:25
  • 1
    The problem is that `triggerHandler()` does not trigger the event handler by simulating a key press on the text input. It is merely executing any "registered" event handlers for the given event. So in your case, the input element never has any characters input into it (and the form does not detect it as being dirty). – Sunil D. May 08 '14 at 20:34
  • Angular unit tests seem to do this: browserTrigger(element, 'keydown'); – aet May 08 '14 at 20:35
  • Found the answer here http://stackoverflow.com/questions/23561259/sending-keydown-to-angular-directive-with-jquery-trigger – spacemigas May 09 '14 at 16:39

1 Answers1

1

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);
  }));
aet
  • 7,192
  • 3
  • 27
  • 25
  • The problem is that I'm not using angular-scenario in my unit tests, just jasmine, so I don't have browserTrigger defined. Nevertheless I'll look at it and try to mimic the desired behavior to see if it works. I'll get back to you, thanks. – spacemigas May 08 '14 at 21:02
  • Couldn't do it, not even with jQuery.trigger(). I will edit question to include a plunker for this. One up for this anyway ;) – spacemigas May 08 '14 at 21:45