You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress 10.11.0无法向contenteditable元素输入内容求助

问题描述
  • 使用Cypress 10.11.0操作CKEditor 5中的可编辑div(带有contenteditable="true"属性),调用type()方法时执行失败,错误提示该div不存在contenteditable属性,但在调用type()前,开发者工具中仍能看到该属性。
  • 当前元素已处于普通HTML状态,排除CKEditor本身问题。

代码示例

const body = 'div.ck-editor__editable[contenteditable="true"]';
cy.get(body)
.should('be.visible')
.click()
.focused()
.wait(10000) // 等待10秒用于检查属性
.type('This is additional text', { force: true })
.type('{ctrl+a}');

错误提示

CypressError: 重试4000ms后超时:期望找到元素:[contenteditable="true"],但始终未找到。查询自元素:<div.ck-editor__editable.ck-editor__editable_inline.ck-blurred>

解决方案

1. 持续断言元素的contenteditable属性

通过.should()强制验证元素始终保持contenteditable="true",避免CKEditor动态修改属性导致Cypress检测失效:

const body = 'div.ck-editor__editable';
cy.get(body)
.should('be.visible')
.should('have.attr', 'contenteditable', 'true') // 确保属性存在且值为true
.click()
.type('This is additional text', { force: true })
.type('{ctrl+a}');

2. 移除focused(),直接操作目标元素

focused()可能会将操作对象切换到CKEditor内部的子元素,导致后续type()作用对象错误,直接对目标div操作更稳妥:

const body = 'div.ck-editor__editable[contenteditable="true"]';
cy.get(body)
.should('be.visible')
.click()
.wait(1000) // 缩短等待时间,建议优先用断言替代固定等待
.type('This is additional text', { force: true })
.type('{ctrl+a}');

3. 调用CKEditor官方API操作(最稳定)

直接通过CKEditor实例的API插入内容,比模拟用户输入更可靠,避免DOM属性变化的影响:

cy.window().then(win => {
  // 根据实际编辑器ID替换`editorId`
  const editor = win.CKEDITOR.instances.editorId;
  editor.setData('This is additional text');
  // 可选:选中全部内容
  editor.getSelection().selectAll();
});

内容的提问来源于stack exchange,提问作者Nikolay Minev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 07:17:47