You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中存储并比较两个值,有没有更优雅的实现方案?

问题描述

我需要先存储一个值,执行操作后断言该值未发生变化。我目前已有可正常运行的代码,但想了解是否存在更优雅的实现方案。

原实现思路

  • 获取页面展示的结果数量(counts),在.then()函数中存储该值
  • 执行用户操作
  • 再次获取页面展示的结果数量(new_counts),在新的.then()函数中存储该值
  • 在第二个.then()函数中对比counts和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)
                    })
            })
    })
})
优化方案

你当前的嵌套写法可以正常运行,缺点是回调嵌套层级过深,后续逻辑复杂之后可读性会大幅下降,推荐用Cypress自带的别名功能存储临时值,把嵌套结构拆平:

describe('存储并对比值', () => {
    it('验证结果总数未变化', () => {
        cy.login()
        cy.visit('url2')
        // 获取初始总数,用as别名存储
        cy.get('.total-count-results').invoke('text').as('initialCount')

        // 执行用户操作
        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(newCount => {
            cy.get('@initialCount').should('eq', newCount)
        })
    })
})

也可以选择用Cypress.env来存储全局临时变量,写法更直接:

describe('存储并对比值', () => {
    it('验证结果总数未变化', () => {
        cy.login()
        cy.visit('url2')
        cy.get('.total-count-results').invoke('text').then(text => {
            Cypress.env('initialCount', 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').should(newCount => {
            expect(newCount).to.eq(Cypress.env('initialCount'))
        })
    })
})

两种写法都完全符合Cypress的异步执行规则,可读性比嵌套回调好很多。


内容的提问来源于stack exchange,提问作者cypher_null

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:06:00