2

I've got a suite that passes or fails seemingly at random, and I think it's probably something to do with the asynch nature of event handling but I can't find a solution. I am testing a simple directive that prevents the default action on the enter keypress (it is being used in a form in the actual app).

Relevant code:

describe('preventSubmitOnEnter', function(){
            var e;
            var e2;
            var element;
            beforeEach(function(){
                element = $compile('<input type="submit" prevent-submit-on-enter />')($rootScope);
                $('body').append(element);
                e = $.Event('keypress');
                e.keyCode = 13;
                e.which = 13;
                $(element).trigger(e);


                e2 = $.Event('keypress');
                e2.keyCode = 110;
                e2.which = 110;
                $(element).trigger(e2);

            });
            afterEach(function(){
                $('input[type="submit"]').remove();
            });

            it('should prevent default event handling for enter keypress and do nothing otherwise', function(){
                expect(e.isDefaultPrevented()).toBe(true);
                expect(e.isPropagationStopped()).toBe(true);
                expect(e2.isDefaultPrevented()).toBe(false);
                expect(e2.isPropagationStopped()).toBe(false);

            });
        })
Derek
  • 722
  • 1
  • 6
  • 16
  • Also, just to clarify, the tests are failing the first two assertions, no other errors are being thrown. – Derek Apr 17 '15 at 21:45
  • Maybe a silly question but why not just use type="button" which doesn't call submit on enter in a form? – shaunhusain Apr 17 '15 at 21:50
  • @shaunhusain that's a fair point, and i might end up doing that, but i'd like to understand why the above is failing off and on. – Derek Apr 17 '15 at 21:52
  • Yeah definitely understandable don't have a clear answer for you there, this does sort of seem like e2e/protractor testing territory since it deals with interacting with input and hitting buttons in a real browser, but not sure what needs to be done in the unit test here to make this be consistent. – shaunhusain Apr 17 '15 at 21:53
  • Possible duplicate of [Why does my jasmine tests fail on this directive?](http://stackoverflow.com/questions/38327752/why-does-my-jasmine-tests-fail-on-this-directive) – Paul Sweatte Apr 22 '17 at 02:26

0 Answers0