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

Javascript 我们如何使用Cypress.io Js自动化框架测试警报和内部显示的文本?,javascript,cypress,Javascript,Cypress,我们如何使用Cypress.io Js自动化框架测试警报和内部显示的文本?我无法理解Cypress文档中的相关示例,请告知 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.

我们如何使用Cypress.io Js自动化框架测试警报和内部显示的文本?我无法理解Cypress文档中的相关示例,请告知

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!')    

    })

})

按照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!')      
    })  

    })

})

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

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

我发现执行此操作的
stub()
方法太混乱、不直观且容易出错。

我无法使用
.stub()
获得可接受的答案,尽管它是
警报的官方Cypress解决方案。显然,我不是这里唯一的一个人,所以我想我应该分享一下我的工作方法,以防它对同舟共济的人有所帮助

扩展@codemon的答案,如果未触发警报,此解决方案将无法通过测试:

   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

如果你碰巧用了这个:,也许我可以帮你省去一些头痛。尝试以下操作以查找未向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()
      })
//例如,模式中需要单击的按钮
//触发警报的事件
cy.get(“”)。单击()
cy.window().then(win=>{

const el=win.Alert.$(`Maybe
cy.on('window:Alert',stub)
来自@Richard Matsen:Awesome,我明白了!但是,如果没有显示警报框,这会不会导致测试失败?我对此表示怀疑。事实上,此测试将无法显示缺少
'window:alert'
事件,因此它是不正确的。谢谢。我在使用存根时也遇到问题,这对我来说是可行的。我相信你的代码中有错误,你我想最后一行应该是:。然后(()=>期望。。。