How can I insert text in a Slate editor with Cypress? The Slate onChange
handler doesn't seem to be called while typing with cy.type()
or cy.clear()
.
How can I insert text in a Slate editor with Cypress? The Slate onChange
handler doesn't seem to be called while typing with cy.type()
or cy.clear()
.
2 Answers
Reset to default 7The Cypress input mands (e.g. cy.type()
and cy.clear()
) work by dispatching input
and change
events - in the case of cy.type()
, one per character. This mimics the behavior of a real browser as a user types on their keyboard and is enough to trigger the behavior of most application JavaScript.
However, Slate relies almost exclusively on the beforeinput
event (see here https://docs.slatejs/concepts/xx-migrating#beforeinput) which is a new browser technology and an event which the Cypress input mands don’t simulate. Hopefully the Cypress team will update their input mands to dispatch the beforeinput
event, but until they do I’ve created a couple of simple custom mands which will trigger Slate’s input event listeners and make it respond.
// mands.js
Cypress.Commands.add('getEditor', (selector) => {
return cy.get(selector)
.click();
});
Cypress.Commands.add('typeInSlate', { prevSubject: true }, (subject, text) => {
return cy.wrap(subject)
.then(subject => {
subject[0].dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: text }));
return subject;
})
});
Cypress.Commands.add('clearInSlate', { prevSubject: true }, (subject) => {
return cy.wrap(subject)
.then(subject => {
subject[0].dispatchEvent(new InputEvent('beforeinput', { inputType: 'deleteHardLineBackward' }))
return subject;
})
});
// slateEditor.spec.js
cy.getEditor('[data-testid=slateEditor1] [contenteditable]')
.typeInSlate('Some input text ');
cy.getEditor('[data-testid=slateEditor2] [contenteditable]')
.clearInSlate()
.typeInSlate('http://httpbin/status/409');
If you need to support other inputTypes, all of the inputTypes supported by Slate are listed in the source code for editable.tsx
As of Cypress v5.5, this now works as expected! No hacks should be required to make it work with Slate.
See https://github./cypress-io/cypress/issues/7088.