如何在Cypress中调用CKEditor 4的setData()方法?
Cypress操作CKEditor4调用setData()方法的解决方案
问题描述
使用Cypress测试集成CKEditor4的项目时,因type方法输入速度慢,尝试通过编辑器body元素获取实例调用setData(),但报错:
Unhandled rejection TypeError: Cannot read properties of undefined (reading 'setData')
原因是CKEditor4的实例并未挂载在编辑器body元素上,不存在ckeditorInstance属性。
解决方案
CKEditor4的实例存储在全局CKEDITOR.instances对象中,可通过编辑器ID直接获取实例并调用setData(),具体实现如下:
方法1:通过全局window对象获取实例
it('向CKEditor4设置内容', () => { cy.visit('https://ckeditor.com/ckeditor-4/demo/') // 等待编辑器iframe加载完成 cy.get('#cke_1_contents iframe').should('be.visible') // 获取全局window对象,从中获取CKEditor实例 cy.window().then((win) => { // 通过编辑器ID获取实例,此处ID为ckdemoarticle(可从iframe的title或页面配置中获取) const editor = win.CKEDITOR.instances.ckdemoarticle editor.setData('<p>测试输入的内容</p>') }) })
方法2:通过iframe的内容窗口获取实例
若页面存在多个编辑器,也可直接从对应的iframe内容窗口获取实例:
it('通过iframe窗口操作CKEditor4', () => { cy.visit('https://ckeditor.com/ckeditor-4/demo/') cy.get('#cke_1_contents iframe') .its('0.contentWindow') // 获取iframe的内容窗口 .then((iframeWin) => { const editor = iframeWin.CKEDITOR.instances.ckdemoarticle editor.setData('<p>通过iframe窗口设置的内容</p>') }) })
关键说明
- CKEditor4的所有实例都保存在全局
CKEDITOR.instances集合中,每个实例的ID对应编辑器初始化时的配置ID(可通过页面元素的data-editor-id属性或iframe的title属性确认)。 - 操作前需确保编辑器已完全加载,可通过
should('be.visible')等待iframe可见来保证实例已初始化。
内容的提问来源于stack exchange,提问作者AMendis
相关产品推荐
相关产品推荐

