我正在使用 Typescript 构建 React Js 应用程序。我正在使用 Cypress 为我的应用程序编写集成测试。我还使用 Typescript 编写 Cypress 测试。我现在正在尝试在 Cypress 测试中设置小型 MCE 编辑器的内容。我正在尝试使用这个库,https://github.com/ForeachOS/cypress-tinymce。但我不能将该库与 TypeScript 一起使用,因为它仅适用于 JavaScript。因此,我查看了设置编辑器值的底层代码。如下。
Cypress.Commands.add('setTinyMceContent', (tinyMceId, content) => {
cy.window().then((win) => {
const editor = win.tinymce.editors[tinyMceId];
editor.setContent(content);
});
});
因此,我尝试在我的 support/index.js 文件中创建该命令的 TypeScript 版本,如下所示。
Cypress.Commands.add('setTinyMceContent', (tinyMceId: string, content: any) => {
cy.window().then((win) => {
const editor = win.tinymce.editors[tinyMceId];
editor.setContent(content);
})
})
但它抱怨如下。
Property 'tinymce' does not exist on type 'AUTWindow'.
我该如何修复它?
如果你看一下
cypress.d.ts
有一个 AUTWindow
的声明
/**
* Window type for Application Under Test(AUT)
*/
type AUTWindow = Window & typeof globalThis & ApplicationWindow
下面是用于用户定义属性的ApplicationWindow
/**
* The interface for user-defined properties in Window object under test.
*/
interface ApplicationWindow { } // tslint:disable-line
您可以通过声明合并添加自己的属性。
在您的
/cypress/support/e2e.d.ts
(Cypress v10) 或 /cypress/support/index.d.ts
(Cypress v9)
/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable<Subject> {
setTinyMceContent(tinyMceId: string, content: any): void
}
}
declare namespace Cypress {
interface ApplicationWindow {
tinymce: any
}
}
还有 @types/tinymce 这可能会很有用。
这里有一个处理动态编辑器 ID 的强大解决方案:
Cypress.Commands.add('getBySelector', (selector, timeout?, ...args) => {
return cy.get(`[data-spec=${selector}]`, { timeout }, ...args);
});
Cypress.Commands.add('setTinyMceContent', (selector, content) => {
// wait for tinymce to be loaded
cy.window().should('have.property', 'tinymce');
// wait for the editor to be rendered
cy.getBySelector(selector).find('editor textarea').as('editorTextarea').should('exist');
// set the content for the editor by its dynamic id
cy.window().then(win =>
cy.get('@editorTextarea').then(element => {
const editorId = element.attr('id');
const editorInstance = (win as any).tinymce.EditorManager.get().filter(editor => editor.id === editorId)[0];
editorInstance.setContent(content);
}),
);
});
谢谢@JohnyDevNull,但就我而言,我必须做一些改变
Cypress.Commands.add('getBySelector', (selector, timeout?, ...args) => {
return cy.get(`[data-testid=${selector}]`, { timeout, ...args });
});
Cypress.Commands.add('setTinyMceContent', (selector, content) => {
// wait for tinymce to be loaded
cy.window().should('have.property', 'tinymce');
// wait for the editor to be rendered
cy.getBySelector(selector)
.find('textarea')
.as('editorTextarea')
.should('exist');
// set the content for the editor by its dynamic id
cy.window().then((win) =>
cy.get('@editorTextarea').then((element) => {
const editorId = element.attr('id');
const editorInstance = (win as any).tinymce.EditorManager.get().filter(
(editor) => editor.id === editorId
)[0];
editorInstance.setContent(content);
})
);
});