ProseMirror / prosemirror

The ProseMirror WYSIWYM editor
http://prosemirror.net/
MIT License
7.53k stars 334 forks source link

Help: how to mock the drop action with js in prosemirror? #1429

Closed fEyebrow closed 8 months ago

fEyebrow commented 8 months ago

I have implemented the function of dragging and dropping images in the editor.

Then I want to add a test for the function. This is my code:

describe<Context>('image', () => {
  beforeEach<Context>((context) => {
    async function upload(file: File): Promise<ImageInfo> {
      return {
        src: 'http://39.105.133.144:5000/api/image/test1/4a835bc8-d18f-4f12-8a2f-ea5f3d059ad4.jpg',
      }
    }
    const editor = new Editor({
      extensions: [
        StarterKit,
        Image.configure({
          upload,
          sizeLimit: IMAGE_LIMIT_SIZE,
        }),
      ],
      content: '',
    })
    context.editor = editor
  })

  it<Context>('Drap image', async ({ editor }) => {
    editor.commands.focus()
    const dataTransfer = new DataTransfer()

    const file = new File([''], 'test.jpg', { type: 'image/jpeg' })
    dataTransfer.items.add(file)

    const dropEvent = new DragEvent('drop', { dataTransfer, bubbles: true })
    const target = editor.view.dom.firstChild as HTMLElement
    target.dispatchEvent(dropEvent)

    await new Promise((resolve) => {
      setTimeout(() => {
        resolve(1)
      }, 500)
    })

    expect(editor.getHTML()).toBe('<p><img src="http://39.105.133.144:5000/api/image/test1/4a835bc8-d18f-4f12-8a2f-ea5f3d059ad4.jpg" alt="" title="" style=""></p>')
  })
})

However, the result of the getHTML function is "\

\

".

I tried to simulate the drop action with js in the development environment, but I found the image wasn't inserted. I tried to insert the image into the editor with the mouse, it was successful.

How to mock the drop action with js in prosemirror?

marijnh commented 8 months ago

JavaScript-created events generally will not trigger the browser's default behavior for the event.

Some browser driver systems allow you to trigger native events. This isn't something ProseMirror will help you with, though.