【问题标题】:Verifying a text on a dialog box with Cypress and Cucumber使用 Cypress 和 Cucumber 验证对话框上的文本
【发布时间】:2021-10-25 20:54:50
【问题描述】:

我正在尝试使用柏树和黄瓜验证对话框上的短信。当测试用例在“它的功能”内时,它工作得非常好。这是示例代码:

    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`)

            })

赛普拉斯日志

【问题讨论】:

    标签: cucumber cypress bdd


    【解决方案1】:

    第一件事是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() 相同的模式。

    【讨论】:

    • 感谢您的详细解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2018-04-25
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多