abdp
abdp

Reputation: 337

How to clear() input fields by overwriting cy.type() command in Cypress

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() command 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]');

Upvotes: 3

Views: 9660

Answers (1)

Josh Bentley
Josh Bentley

Reputation: 91

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

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

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

Heres an example you could add to commands.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 commands. If you prefer the logging be like the original type command 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 command that calls the clear command then the type command 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]');
  

Upvotes: 5

Related Questions