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

如何在Cypress中按指定次数点击按钮,测试博客点赞排序功能

问题根因

代码核心错误是混淆了Cypress中get()和find()的作用范围:

  • cy.get()始终从整个文档根节点开始查找元素,不会继承之前链式调用的元素上下文
  • 你每次执行.get('.blog-like-button')加上{ multiple: true }参数,都会点击当前页面上所有可见的点赞按钮,而不是你前面选中的对应博客的点赞按钮,所以最终统计的点赞次数和预期不符。

修正方案

把对应博客范围内的元素查找替换为find(),同时优化不必要的强制等待、移除多余的multiple参数,修改后代码如下:

it('the blogs are ordered in descending order of likes', function() {
    // 创建三个测试博客
    cy.createBlog({
        title: 'The Perks of Being a Wallflower',
        author: 'Emma Watson',
        url: 'www.blank.org',
    })
    cy.createBlog({
        title: 'The Life of Pi',
        author: 'Yann Martel',
        url: 'www.pi.com',
    })
    cy.createBlog({
        title: 'Deep Dive into the World of Containers',
        author: 'GDG',
        url: 'www.gdg.com',
    })

    // 给第一个博客点3次赞
    cy.contains('The Perks of Being a Wallflower')
      .parent() // 可根据实际DOM结构调整,确保锁定当前博客的容器
      .as('blog1')
    cy.get('@blog1').contains('view').click()
    cy.get('@blog1').find('.blog-like-button').click()
    cy.get('@blog1').find('.blog-like-button').click()
    cy.get('@blog1').find('.blog-like-button').click()

    // 给第二个博客点1次赞
    cy.contains('The Life of Pi')
      .parent()
      .as('blog2')
    cy.get('@blog2').contains('view').click()
    cy.get('@blog2').find('.blog-like-button').click()

    // 给第三个博客点2次赞
    cy.contains('Deep Dive into the World of Containers')
      .parent()
      .as('blog3')
    cy.get('@blog3').contains('view').click()
    cy.get('@blog3').find('.blog-like-button').click()
    cy.get('@blog3').find('.blog-like-button').click()

    cy.reload()
    // 后续补充排序校验逻辑即可
})

额外优化建议

  • 不要使用固定时长的cy.wait(),可以通过should('be.visible')之类的断言等待元素加载完成,测试稳定性更高
  • 给每个博客的外层容器加统一的类名比如.blog-item,后续查找元素时更精准,不需要依赖parent()层级匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:36:03