Search code examples
javascriptautomated-testscypressprompt

How to handle a windows prompt in a test automation using Cypress?


I am new to using Cypress for web automation. I am still scouring through the internet looking for answers to this but I cannot find a solution that works for me.

This is what I'm trying to do in my test:

  • User clicks a link.
  • A new tab is opened and a windows prompt appears, requesting user input (username, password).
    (Since Cypress doesn't allow opening new tabs, I've removed the target attribute.)
  • Upon logging in successfully, the page has a download button.
  • User clicks on the download button.

The first struggle - I could not enter values into the windows prompt. In the below code, I was trying to see if the 'Sign In' button on the windows prompt would be clicked, but it was not.

cy.window().then(win => {
    cy.get('@documentPassword').then((finalPassword) => {
        const stub =cy.stub(win, 'prompt')
        stub.returns('test')
        cy.get('button#signin').click()
    })
})

I got an Assertion Error: Timed out retrying after 25000ms: Expected to find element: button#signin, but never found it.

After no luck with this, I moved on to another suggestion.


The second struggle - I tried putting the username and password into the link, like this: https://username:[email protected]. Just to note, when I paste the link manually into a browser, it works. To test this out, this what I had done:

cy.visit('https://mailtrap.io')
// ...other steps
cy.forceVisit('https://username:[email protected]')

I added a custom command forceVisit to the commands.js file:

Cypress.Commands.add('forceVisit', url => {
    cy.window().then(win => {
        return win.open(url, '_self'); 
      });
});

The result is the second url does not load.

Hoping for any insight from you guys. Thanks in advance.


Solution

  • This works for me:

    cy.visit('https://mytestingwebsite.com', {
      auth: {
       username: 'username',
       password: 'password'
      }
    })
    

    This didn't work for me the first time I tried it because I still passed the credentials in the url.