Sending native key events to code mirror

For testing our project, I’d like to send “key events” to code mirror. I want to mimic an actual user typing as close as possible. It appears though, that code mirror only listens to native key events (not jquery for example), which are pretty tricky to fire. I haven’t been able to get them working (I’ve tried a few libraries and I’ve also tried creating and firing the events myself).

The current way I’m satisfying this needs is as follows:

  • Iterate over each key map internal to code mirror
    • If there is a key handler for this key, call the handler directly and deem this key “handled” assuming the handler doesn’t return CodeMirror.Pass
  • If the key wasn’t “handled” above, then manually set the content of the editor and cursor to simulate “typing” this key

I’m worried about this though because it seems pretty fragile.

I realize that sending native key events might be a bit out of the scope of this forum, but I’m wondering if people have encountered something similar to this or could point me in the right direction. Perhaps code mirror has some internal testing code that could be useful here?

Thanks for the help!


You can use the triggerOnKeydown, triggerOnKeyPress, and triggerOnKeyUp methods. These exist for testing purposes only, and don’t precisely simulate actual key events (there’s no default behavior – if you simulate a keypress that isn’t bound to any command, the corresponding character won’t appear), but they can be used to test key bindings.