如何使用Cypress测试一个弹出框提示?

7

我正在使用Cypress测试数据表单,但卡在了一个在页面上显示警报的步骤上。

这是测试,但它并没有起作用。

describe('Alert is displayed with warning text', () => {

  it('Assert that the alert is displayed after entering data', () => {
    cy.visit('/')     
    cy.get('input').type('some data').blur()
    cy.on ('window:alert', (text) => {
      cy.wrap(text).should('eq', 'alert text')
    })    
  })
})

我该如何测试页面上弹出的警告框?

2个回答

6
你可以修改你的代码,使用expect()代替should()
问题在于Cypress不喜欢事件监听器中的命令。
你必须使用done()回调来避免在警报未触发时出现错误的正面结果
describe('Alert is displayed with warning text', () => {

  it('Assert that the alert is displayed after entering data', (done) => {
    cy.visit('/')     

    cy.on ('window:alert', (text) => {
      expect(text).to.eq('alert text')
      done()                              // waiting for event, fails on timeout    
    )

    cy.get('input').type('some data').blur()
  })
})

4

cy.on('window:alert') 代码是一个事件监听器

与其他命令添加回调不同,你可以添加存根并检查存根函数是否被调用以及它所呈现的文本。

由于它是一个监听器,因此必须在触发事件之前设置它。

describe('Alert is displayed with warning text', () => {

  it('Assert that the alert is displayed after entering data', () => {
    cy.visit('/')     

    const stub = cy.stub()
    cy.on ('window:alert', stub)

    cy.get('input').type('some data').blur()

    // wait for the event to be handled
    cy.then(() => {                       
      expect(stub.getCall(0)).to.be.calledWith('alert text')
    })

  })
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接