BuildTester1
BuildTester1

Reputation: 625

How to mock an event like 'keypress' or 'keydown' in an AngularJS unit test?

I've looked at previous articles but they seem to be updated, and I've hit a brick wall. Can anyone help me find a solution?

I've got a directive that has some events bind. It's a credit card number filter, so it adds a space every 4 numbers to make it easier to read. I'm trying to test it in karma/jasmine by feeding it the number 5555555555554444, and expect response for $viewValue of 5555 5555 5555 4444, but can't find a way to trigger the event to fire.

I've tried $setViewValue, $render(), $digest(), and I've tried some of the solutions from StackOverflow (over a year old) but they don't seem to work.

Is the only solution to use jQuery? And if so, does that jQuery solution still work? I've been trying to do this without including jQuery into my unit tests.

A code sample of what I'm working with:

    elem.bind('keypress', parseKeyPress);
    elem.bind('keydown contextmenu', parseKeyDown);
    elem.bind('cut paste', parseCutPaste);

    var parseHandler= function (value) {
      return value ? returnNumbersOnly(value) : '';
    };
    ctrl.$parsers.unshift(parseHandler);
    ctrl.$formatters.unshift(parseHandler);

Thoughts?

Upvotes: 0

Views: 1317

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190976

You should use elem.trigger(...) to emit those events as needed.

Upvotes: 1

Related Questions