soccerway
soccerway

Reputation: 11991

Is it possible to type inside the textbox displaying in a prompt in Cypress and click on ok button

Is it possible to type inside the textbox displaying in an alert using Cypress command and the click on ok inside alert. The below test display the alert message but didn't do anything.

describe('Type some text inside the textbox in an alert', function() {
  it.only('Type some text inside the textbox test', function() {
    cy.visit('http://sometesturl.com')
    const stub = cy.stub()
     cy.on ('window:alert', stub)
     cy
      .get('#pidforinput').click()
      .then(($stub) => {
      const myWin = $stub.find('input');
      cy.wrap(myWin ).type("This is a text box");
    })
  })
})

//Below is my js code to display alert and textbox inside

function promptMessage() {
    var favColor = prompt("What is your favorite color?", "");
    if (favColor != null){      
    alert("Your favorite color is " + favColor);        
    }
    else {
    alert("You did not specify your favorite color");
    }
}

<input id="pidforinput" type="button" onclick="promptMessage()" value="Click here to specify your favorite color" />

Upvotes: 2

Views: 2945

Answers (1)

Nimish Gupta
Nimish Gupta

Reputation: 1051

So right now according to the documentation of Cypress you can use stubs to change the behaviour of prompts like this

cy.visit('http://localhost:3000', {
  onBeforeLoad(win) {
    cy.stub(win, 'prompt').returns('my custom message')
  }
})

cy.window().its('prompt').should('be.called')
cy.get('any_selector').should('have.value', 'my custom message')

Check this for further info

Upvotes: 2

Related Questions