代码之家  ›  专栏  ›  技术社区  ›  soccerway

如何使用Cypress.io Js自动化框架测试警报和内部显示的文本?

  •  4
  • soccerway  · 技术社区  · 6 年前

    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!')    
    
        })
    
    })
    
    2 回复  |  直到 6 年前
        1
  •  7
  •   soccerway    6 年前

    使用Richard Matsen建议的cy.stub()方法找出答案:

    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!')      
        })  
    
        })
    
    })
    
        2
  •  4
  •   codemon    5 年前

    这是一种更简单、更直观的方法:

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

    我找到了 stub() 这样做的方法太混乱,不直观和容易出错。

        3
  •  3
  •   chatnoir    5 年前

    我不能用 .stub() 工作,尽管它是柏树的官方解决方案 alert . 显然,我不是一个人在这里,所以我想我会分享我的解决方法,以防有人在同一条船上。

       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
    
        4
  •  0
  •   jameseg    5 年前

    如果你碰巧使用这个: alert.js ,也许我可以帮你省点头痛。尝试以下操作以查找未注册到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()
          })