Repository navigation
How to test PlateJs Marks with React Testing Library #5089
|
I don't seem to be able to make this work, and any help will be much appreciated. My Editor looks something like this: and the controls look like I would like to test the interaction with these buttons. So, my test looks like By debugging, I can confirm that onClick() is actually called, which should, trigger a re render. That re render does not take place, and my tests fail. I have tried everything you can think of.
Nothing works. Under the hood, useMarkToolbarButtonState simply invokes editor.api.hasMark(nodeType), which I have also tested, but within the context of my tests, returns falsy. No idea! Is the reference to the editor lost somehow? Please help :) |
Replies: 1 comment 1 reply
|
The root cause is that Plate's own tests don't test toolbar clicks with RTL for this reason. Instead, marks are tested at the transform level [2]: const editor = createSlateEditor({
plugins: [BoldPlugin],
value: [{ children: [{ text: 'hello' }] }],
selection: {
anchor: { path: [0, 0], offset: 0 },
focus: { path: [0, 0], offset: 5 },
},
});
editor.tf.toggleMark('bold');
expect(editor.api.hasMark('bold')).toBe(true);If you still want to test through click interactions, you need to manually set a valid selection on the editor before clicking the button: // After render, set selection programmatically
act(() => {
editor.tf.select({
anchor: { path: [0, 0], offset: 0 },
focus: { path: [0, 0], offset: 5 },
});
});
await userEvent.click(button);But even this may not work reliably since JSDOM doesn't maintain ContentEditable focus/selection state the way a real browser does. For full interaction testing with toolbar buttons, you'd want a browser-based test runner like Playwright or Cypress. To reply, just mention @dosu. Share context across your team and agents. Try Dosu. |
The root cause is that
toggleMarkimmediately returns wheneditor.selectionisnull[1]. In JSDOM (what React Testing Library uses), ContentEditable selection behavior isn't fully implemented, so clicking the toolbar button firesonClickbut the editor has no valid selection — the mark command becomes a no-op, no state changes, no re-render.Plate's own tests don't test toolbar clicks with RTL for this reason. Instead, marks are tested at the transform level [2]: