使用 Cypress 和 Cucumber 验证对话框中的文本

Verifying a text on a dialog box with Cypress and Cucumber

我正在尝试使用柏树和黄瓜验证对话框中的文本消息。当测试用例处于“它的功能”范围内时,它工作得非常好。这是示例代码:

    it ('Verify if the Login is successful', function()
    {
       
        cy.visit('loginTest.html')
        cy.get('#username').type('shahin')
        cy.get('#password').type('tala')
        cy.contains('Login').click() 
        cy.on('window:alert', (str) => {
            expect(str).to.equal(`Login Successfully`)
          })
    })

但是,当我添加 BDD 关键字时,该函数似乎根本没有得到评估。 它适用于 When 但不适用于 Then 场景。我认为它需要以不同的方式在 Js 中处理。我也上传了柏树日志。下面是代码:

        When('I click on the login button', () => {
            cy.contains('Login').click()
        })
        Then('Successful POP up message should be displayed', () => {
            cy.on('window:alert',  (str) =>  {
                expect(str).to.equal(`Login Successfully`)

            })

赛普拉斯原木

首先是 cy.on('window:alert'... 是一个被动事件侦听器,在应用程序发出事件之前它不会执行任何操作。

这意味着您需要在事件触发之前设置它(例如登录点击),

When('I click on the login button', () => {
  cy.on('window:alert', ...something here...)   // set up the event listener
  cy.contains('Login').click()                  // action that triggers the event
})

如果您在事件侦听器的回调中执行 expect(),它会扰乱您的 BDD 流程(Then() 是多余的)。

使用存根来捕获事件,并断言 Then().

中的存根属性
let stub  // declare outside so it's visible in both When and Then

When('I click on the login button', () => {
  stub = cy.stub()              // set stub here (must be inside a test)
  cy.on('window:alert', stub)   // capture call 
  cy.contains('Login').click()  
})

Then('message is displayed', () => {
  expect(stub).to.have.been.calledWith('Login Successful')
})

为什么 it() 有效?

本质上,it() 所有代码都在一个块内,而 When() Then().

则为两个块

异步命令排队等候稍后执行,但同步命令 cy.on() 立即执行 - 即使它是最后一行它首先执行。

it('...', () => {

  // Queued and executed (slightly) later
  cy.visit('loginTest.html')
  cy.get('#username').type('shahin')
  cy.get('#password').type('tala')
  cy.contains('Login').click() 

  // executed immediately (so actually first line to run)
  cy.on('window:alert', (str) => {
    expect(str).to.equal(`Login Successfully`)
  })
})

When()Then() 块按顺序执行,因此您不会得到与 it().

相同的模式