【问题标题】:Cypress Best Practice - Store and compare two values赛普拉斯最佳实践 - 存储和比较两个值
【发布时间】:2022-03-11 12:40:05
【问题描述】:

我想存储一个值,然后执行一个操作并断言该值没有改变。我确实有一个有效的代码,但如果有更优雅的解决方案,我想提供意见。

基本思路是:

  • 获取显示的数字或结果('counts'),将其存储在 .then() 函数中
  • 改变用途
  • 获取显示的结果数 ('new_counts'),将其存储在新的 .then 函数中
  • 比较第二个 .then() 函数中的计数和 new_counts
describe('Store and compare a value', () => {
    it('store and compare', () => {

        cy.login()
        cy.visit('url2')
        cy.get('.total-count-results').invoke('text')
            .then((text) => {
                const counts = text 
                cy.get('.medium.col100 > .filterwrapper > input').type('Test Dummy',{force: true})
                cy.get('.medium.col100 > .filterwrapper > input').type('{enter}')
                cy.get('.total-count-results').invoke('text')
                    .then((text) => {
                        const new_counts = text
                        expect(new_counts).to.eq(counts)
                    })
            })
    })
})

这是我能想到的最好的处理异步性的方法。

【问题讨论】:

  • 您可以通过实际命名箭头函数参数来简化您想要调用的变量,然后直接断言而不是嵌套另一个,否则这就是docs.cypress.io/guides/core-concepts/variables-and-aliases 的建议。
  • 谢谢。我将再次查看文档的那部分。另外,感谢您编辑我的帖子以更好地符合 SO 标准!

标签: javascript cypress


【解决方案1】:

我认为不需要别名。这是我在本地测试的解决方案。我将大部分代码保存在 Alapan Das 的answer 中,以便比较。对我来说,它似乎更简洁,更容易阅读没有别名。

describe('Store and compare a value', () => {
    it('store and compare', () => {  
        cy.login()
        cy.visit('url2')
        cy.get('.total-count-results').invoke('text')
            .then((previousText) => {
                cy.get('.medium.col100 > .filterwrapper > input').type('Test Dummy',{force: true})
                cy.get('.medium.col100 > .filterwrapper > input').type('{enter}')
                cy.get('.total-count-results').invoke('text').should("eq", previousText)
            })
    })
})

【讨论】:

    【解决方案2】:

    您可以为此使用别名并执行以下操作:

    describe('Store and compare a value', () => {
      it('store and compare', () => {
        cy.login()
        cy.visit('url2')
        cy.get('.total-count-results').invoke('text').as('counts')
        cy.get('.medium.col100 > .filterwrapper > input').type('Test Dummy', {
          force: true,
        })
        cy.get('.medium.col100 > .filterwrapper > input').type('{enter}')
        cy.get('.total-count-results').invoke('text').as('new_counts')
        cy.get('@counts').then((counts) => {
          cy.get('@new_counts').then((new_counts) => {
            expect(new_counts).to.eq(counts)
          })
        })
      })
    })
    

    【讨论】:

    • 谢谢。这看起来肯定好多了。我不确定如何正确使用别名,但将来我会尝试实现这个功能!
    • 第二个别名引用应该是“cy.get('@new_counts')”
    • 感谢您指出。我已经纠正了错字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    相关资源
    最近更新 更多