Simulate Keypress Event

I am creating Integration Tests for ProseMirror and I would like to simulate typing to confirm a few things. Here is an example of my Mocha code:

it('Plugin can Handle Simulated Event', () => {
  let value = false
  const test = new Plugin({
    props: {
      handleDOMEvents: {
        keydown (view, event) {
          value = true
          console.log(view, event)
        }
      }

    }

  })
  tempEditor({ plugins: [test] })
  const editor = $('.ProseMirror')
  editor.focus()



  // Issue is Here
  editor.keydown( function(e) { console.log(e)})
  const e = $.Event('keydown')
  e.which = 66 // B 
  editor.trigger(e)

  value.should.equal(true)
})

image

When I run this code, the editor is focused but the editor doesn’t seem to recognize the keydown event and the test fails as the keydown event is never handled by the plugin. I know the event fires because the event is printed by the jquery listener.

I’m not familiar enough with jQuery to see what might be going on here, but it’s possible that some aspect of the simulated event causes ProseMirror to ignore it (see for example eventBelongsToView in the view code).

It seems JQuery wasn’t supported in my test environment for some reason. So I switched to vanilla events and it worked! I am now having another issue with actually adding text through the keypress event. image

The code I wrote is this:


it('Text can be inserted by Event', () => {
  const view = tempEditor({ handleKeyDown: (_view, event) => console.log(event) })
  const editor = document.querySelector('.ProseMirror')

  const event = new KeyboardEvent('keydown', { keyCode: 66, bubbles: false })
  editor.dispatchEvent(event)
  view.state.doc.firstChild.textContent.should.equal('B')
})

The keypress event isn’t handled and won’t insert text. ProseMirror looks for actual text input into its editable element, which you can’t simulate by firing events.