web-dev-qa-db-fra.com

Comment pouvons-nous tester l'alerte et le texte à l'intérieur s'affiche en utilisant le cadre d'automatisation Cypress.io Js?

Comment pouvons-nous tester l'alerte et le texte à l'intérieur s'affiche en utilisant le cadre d'automatisation Cypress.io Js? Je ne peux pas comprendre l'exemple pertinent dans la documentation de Cypress, veuillez en informer.

describe('Test an alert and the text displaying', function() {
it('Verify alert and its text content', function(){
    cy.visit('http://www.seleniumeasy.com/test/javascript-alert-box-demo.html')     
    cy.get('button').contains('Click me!').click()
    cy.on ('window:alert', 'I am an alert box!')    

    })

})
10
soccerway

Compris la réponse en utilisant la méthode cy.stub () comme conseillé par Richard Matsen:

describe('Test an alert and the text displaying', function() {
it('Verify alert and its text content', function(){
    cy.visit('http://www.seleniumeasy.com/test/javascript-alert-box-demo.html')    

    const stub = cy.stub()  
    cy.on ('window:alert', stub)
    cy
    .get('button').contains('Click me!').click()
    .then(() => {
      expect(stub.getCall(0)).to.be.calledWith('I am an alert box!')      
    })  

    })

})
7
soccerway

C'est une manière beaucoup plus simple et plus intuitive:

cy.on('window:alert', (str) => {
  expect(str).to.equal(`This is an alert box!`)
})

J'ai trouvé la méthode stub() pour faire cela trop compliquée, peu intuitive et sujette aux erreurs.

4
codemon

Je n'ai pas pu obtenir la réponse acceptée en utilisant .stub() pour travailler, bien que ce soit la solution officielle de Cypress pour alert. Apparemment, je ne suis pas seul ici, alors j'ai pensé partager ma solution au cas où cela aiderait quelqu'un dans le même bateau.

Développant la réponse de @ codemon, cette solution de contournement va échouer au test si aucune alerte n'a été déclenchée:

   var alerted = false;
   cy.on('window:alert', msg => alerted = msg);

   cy.get('button').contains('Click me!').click() //or whatever code that triggers alert
   .then( () => expect(alerted).to.match(/clicked!/); //or whatever regex is appropriate
3
chatnoir

Si vous utilisez ceci: alert.js , alors je peux peut-être vous éviter quelques maux de tête. Essayez quelque chose comme ceci pour trouver l'élément qui n'est PAS enregistré avec le DOM:

// for example, a button in the modal that needs clicking

// the event that fires the alert
 cy.get('<some element>').click()

 cy.window().then(win => {
        const el = win.Alert.$(`<whatever element you're looking for>`)
        cy.wrap(el)
          .find('button')
          .contains('Confirm')
          .click()
      })
0
jameseg