javascriptreactjsjestjsckeditor

How to test a CKEditor change


I'm using a CKEditor component from ckeditor4-react in my application. I'd like to create a jest test that will use react-testing-library to write some stuff inside this CKEditor component.

At the moment, my component contains code like:

const handleChange = (event: any) => {
    setBody(event.editor.getData());
};

<CKEditor
  onChange={handleChange}
  data-testid="ckeditor-textfield"
/>

This works fine when testing manually.

Within my Jest test, I've got the following:

const editorText = screen.getByTestId('ckeditor-textfield');
fireEvent.change(editorText, { target: { value: 'Email body text' } });

However, this doesn't work and I get an error:

TestingLibraryElementError: Unable to find an element by: [data-testid="ckeditor-textfield"]

If I try a different way to get the editor text field by doing:

const editorText = document.getElementsByClassName('cke_editable')[0];

I get the following error:

Unable to fire a "change" event - please provide a DOM element.

How can I test the input field for a CKEditor component?


Solution

  • This isn't a very elegant solution but I've initialised the CKEditor data when running the jest unit tests as such:

    <CKEditor
       initData={ process.env.JEST_WORKER_ID !== undefined && <p>unit tests data</p> }
    />