如何使用 Cypress 测试警报

Vag*_*evi 7 alert cypress

我正在使用 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')
    })    
  })
})
Run Code Online (Sandbox Code Playgroud)

如何测试页面上弹出的此警报?

Tes*_*ick 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()
  })
})
Run Code Online (Sandbox Code Playgroud)