赛普拉斯的自定义命令允许覆盖现有命令
https://docs.cypress.io/api/cypress-api/custom-commands.html#Overwrite-Existing-Commands
另外,clear() 命令只是 .type('{selectall}{backspace}'); 的别名。
https://docs.cypress.io/api/commands/clear.html#Syntax
因此,您可以做的是覆盖 type 命令以始终在输入任何其他内容之前输入 {selectall}{backspace}。
这是一个可以添加到 commands.js 的示例:
Cypress.Commands.overwrite("type", (originalFn, element, text, options) => {
const clearedText = `{selectall}{backspace}${text}`;
return originalFn(element, clearedText, options);
});
这将更改日志记录以包含额外的命令。如果您希望日志记录类似于原始类型命令,您可以对其进行一些自定义。
Cypress.Commands.overwrite("type", (originalFn, element, text, options) => {
const clearedText = `{selectall}{backspace}${text}`;
options = { ...options, log: false };
Cypress.log({
$el: element,
name: "type",
message: text,
});
return originalFn(element, clearedText, options);
});
编辑:
由于上面的建议不处理日期输入和其他我要做的只是创建一个新的 cypress 命令,该命令调用 clear 命令,然后依次调用 type 命令。
Cypress.Commands.add("clearThenType", { prevSubject: true }, (subject, text) => {
cy.wrap(subject).clear().type(text);
}
);
例子:
cy.get('@firstname')
.clearThenType('John')
.get('@lastname')
.clearThenType('Doe')
.get('@email')
.clearThenType('john.doe@email.com');