Skip to content
This repository has been archived by the owner on Feb 6, 2023. It is now read-only.

What is the best way to simulate content change within an editor test? #743

Open
jdetch opened this issue Oct 26, 2016 · 4 comments
Open

Comments

@jdetch
Copy link

jdetch commented Oct 26, 2016

If I simulate a change or keypress event on a draft editor node or it's contenteditable node, why don't I see onChange get called?

A simple example of what I would expect to work:

describe('MyEditor', () => {
  it("calls onChange when content is edited", () => {
    const content = ContentState.createFromText("Any random string")
    const onChangeSpy = spyOn(MyEditor.prototype, 'onChange')
    const editor = renderIntoDocument(<MyEditor contentState={content}/>)
    const editorNode = findDOMNode(editor)
    Simulate.change(editorNode, {target: { value: 'x'}})
    expect(onChangeSpy).toHaveBeenCalled()
    expect(editor.state.editorState.getCurrentContent().getPlainText()).toContain('x')
  })  
})

I tried doing all kinds of things with Simulate (keyPresses, keyDowns, changes, etc.), but nothing seemed to actually change the value of the content.

@Datamine
Copy link

@jdetch I'm having the same issue. Did you manage to simulate changes/keypresses?

@kenju
Copy link

kenju commented Apr 28, 2017

Draft.js's components does not change its content with keypress, keydown or change events, which are mostly used events for <input/> though. Draft.js does not rely on <input />.

The rendering of the DOM representation is driven entirely from the EditorState object, not those DOM events.

keydown and keypress events are not used for character insertion. Rather, the React polyfill for beforeInput is used for this: https://github.com/facebook/draft-js/blob/master/src/component/handlers/edit/editOnBeforeInput.js.

I suggest following this issue
#325 (comment)

@kenju
Copy link

kenju commented May 10, 2017

FYI

Updated the solution for simulating Keyboard Event for draft.js ->
#325 (comment)

@hernang87
Copy link

The solution I found for most text input is to get the react component and trigger onBeforeInput and onInput manually.

const draft = document.getElementsByClassName('container').getElementsByClassName('public-DraftEditor-content')[0];

Find which element inside draft includes __reactInternal and then for each char:

component.onBeforeInput({ data: char, preventDefault: noop });
component.onInput();

This doesn't work for accents unfortunately but there might be a way to do it with this approach.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants