如何通过重写Cypress中的cy.type()命令来清除()输入字段



对于我的Cypress e2e测试:

每次我必须在输入中键入内容时,我都必须通过在type()之前调用clear()来手动清除输入

我必须清除,因为在这一步骤之前还有其他负面测试,可能会在这些字段中留下无效数据。

在每次使用type()方法之前,我如何将type()命令改写为clear()输入

cy.get('@firstname')
.clear()
.type('John')
.get('@lastname')
.clear()
.type('Doe')
.get('@email')
.clear()
.type('john.doe@email.com');

Cypress的自定义命令允许覆盖现有命令
https://docs.cypress.io/api/cypress-api/custom-commands.html#Overwrite-现有命令

此外,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);
});

编辑:

由于上面的建议不处理日期输入和其他内容,我只需要创建一个新的柏树命令,依次调用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');

最新更新