I am writing tests for an AngularJS directive which fires events of a <textarea>
when certain keys are pressed. It all works fine per my manual testing. I want to be good and have a full unit-test suite too, but I have run into a problem I can't solve on my own:
I want to send a specific keyCode
in my triggerHandler()
call in my test, but I can't find a way to specify the key that actually works. I am aware of a lot of questions and answers on the topic of building and sending events with specific data, but none of them work on my setup:
My setup
- Karma test runner
- PhantomJS browser running the tests (but also tried Firefox and Chrome without success)
- I'm not using jQuery and I'm hoping there is a regular JS solution. There must be!
Test code
var event = document.createEvent("Events");
event.initEvent("keydown", true, true);
event.keyCode = 40; // in debugging the test in Firefox, the event object can be seen to have no "keyCode" property even after this step
textarea.triggerHandler(event); // my keydown handler does not fire
The strange thing is, I can type the first 3 lines into the console in Chrome and see that the event is being created with the keyCode
property set to 40.
So it seems like it should work.
Also, when I call the last line like this textarea.triggerHandler("keydown");
it works and the event handler is triggered. However, there is no keyCode
to work with, so it is pointless.
I suspect it may be something to do with the nature of the test running against a DOM that is different to a regular page running in the browser. But I can't figure it out!