Clear Input Field Flake

📺 Watch the explanation for this recipe at Clear Input Element Flakeopen in new window.

<input id="answer" placeholder="Enter your answer" value="00" />
  setTimeout(() => {
    const input = document.getElementById('answer')
    input.value = 777
  }, 1000)

At first, we try to clear the input field and type our value as quickly as we can.

// has race condition with the application
cy.get('#answer').clear().type(42).should('have.value', 42)

Instead we want to check if the application has finished setting its initial value.

// wait for the app to finish setting the initial value
// which is different from the static attribute
  .should('have.attr', 'value')
  .then((staticValue) => {
      .should('not.equal', staticValue)
// now we can clear the input field safely
cy.get('#answer').clear().type(42).should('have.value', 42)

See also