admin管理员组

文章数量:1332896

For my Cypress e2e tests:

Everytime I have to type something in an input, I have to manually clear the input by calling clear() before type()

I have to clear because there are other negative tests before this step which might have left invalid data in those fields.

How can I overwrite the type() mand to clear() the input everytime before I use the type() method

cy.get('@firstname')
  .clear()
  .type('John')
  .get('@lastname')
  .clear()
  .type('Doe')
  .get('@email')
  .clear()
  .type('[email protected]');

For my Cypress e2e tests:

Everytime I have to type something in an input, I have to manually clear the input by calling clear() before type()

I have to clear because there are other negative tests before this step which might have left invalid data in those fields.

How can I overwrite the type() mand to clear() the input everytime before I use the type() method

cy.get('@firstname')
  .clear()
  .type('John')
  .get('@lastname')
  .clear()
  .type('Doe')
  .get('@email')
  .clear()
  .type('[email protected]');
Share Improve this question asked Jul 25, 2020 at 1:36 abdpabdp 3451 gold badge5 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Cypress's custom mands allows for overwriting existing mands
https://docs.cypress.io/api/cypress-api/custom-mands.html#Overwrite-Existing-Commands

Also, the clear() mand is just an alias for .type('{selectall}{backspace}'); https://docs.cypress.io/api/mands/clear.html#Syntax

So what you could do is overwrite the type mand to always type {selectall}{backspace} before anything else is typed.

Heres an example you could add to mands.js:

Cypress.Commands.overwrite("type", (originalFn, element, text, options) => {
  const clearedText = `{selectall}{backspace}${text}`;

  return originalFn(element, clearedText, options);
});

This will change the logging to include the extra mands. If you prefer the logging be like the original type mand you could customize it a bit.

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);
});

Edit:

Since the suggestion above does not handle date inputs and others what I would do is just create a new cypress mand that calls the clear mand then the type mand sequentially.

Cypress.Commands.add("clearThenType", { prevSubject: true }, (subject, text) => {
    cy.wrap(subject).clear().type(text);
  }
);

Example:

cy.get('@firstname')
  .clearThenType('John')
  .get('@lastname')
  .clearThenType('Doe')
  .get('@email')
  .clearThenType('[email protected]');
  

本文标签: javascriptHow to clear() input fields by overwriting cytype() command in CypressStack Overflow