Cypress web自动化38-alert 弹窗 cy.on('window:alert', stub)

前言

当页面上出现 alert 弹窗时候,Cypress 自动接受 alert, 运行代码的时候虽然看不到弹窗页面,但是依然可以对文本内容断言

Alert 弹窗

Cypress 自动接受 alert,但您仍然可以对文本内容进行断言,使用示例

// app code
$('button').on('click', (e) => {
  alert('hi')
  alert('there')
  alert('friend')
})

it('can assert on the alert text content', () => {
  const stub = cy.stub()

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

  cy
    .get('button').click()
    .then(() => {
      expect(stub.getCall(0)).to.be.calledWith('hi')
      expect(stub.getCall(1)).to.be.calledWith('there')
      expect(stub.getCall(2)).to.be.calledWith('friend')
    })
})

百度搜索案例

百度-搜索设置-保存设置,弹出alert

/**
 * Created by dell on 2020/6/9.
 * 作者:上海-悠悠 交流QQ群:939110556
 */

describe('baidu alert', function() {

    before( function() {
        cy.visit("https://www.baidu.com/")

        cy.get("#s-usersetting-top").trigger('mouseover')  // 鼠标悬停
        cy.contains("搜索设置").click()
    })


    it('assert alert text', () => {
      const stub = cy.stub()
      cy.on('window:alert', stub)

      cy
          .contains("保存设置").click()
          .then(() => {
          expect(stub.getCall(0)).to.be.calledWith('已经记录下您的使用偏好')
        })
    })

    })

运行结果

posted @ 2020-06-10 14:00  上海-悠悠  阅读(2065)  评论(0编辑  收藏  举报