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

如何在Cypress中验证一段文本包含另一段随机文本?

在Cypress中验证文本包含随机选中的目标文本

原代码存在的问题

  1. 异步变量传递错误:Cypress命令是异步执行的,用let声明的变量无法跨then正确传递值,后续步骤可能拿到未赋值的变量。
  2. 断言语法错误:Chai断言的contain方法不需要第一个参数'text',正确用法是直接传入要验证的包含文本。

修正后的代码方案

方案一:使用Cypress别名传递值

// 生成1-19之间的随机索引
const randomCityIndex = Math.floor(Math.random() * (20 - 1) + 1)

// 获取随机城市文本并设置别名
cy.xpath("div").eq(randomCityIndex).invoke('text').as('targetCity')

// 点击选中的城市(如伦敦、东京、柏林等)
cy.xpath("div").eq(randomCityIndex).click()

// 获取目标句子并验证包含城市名
cy.xpath("p").invoke('text').then((sentence) => {
  cy.get('@targetCity').then((cityName) => {
    // 去除文本前后空白字符,避免因空格导致断言失败
    expect(sentence).to.contain(cityName.trim())
  })
})

方案二:嵌套then保证异步顺序

const randomCityIndex = Math.floor(Math.random() * (20 - 1) + 1)

cy.xpath("div").eq(randomCityIndex).invoke('text').then((cityName) => {
  // 在获取城市名后再执行点击和断言,保证顺序
  cy.xpath("div").eq(randomCityIndex).click()
  
  cy.xpath("p").invoke('text').then((sentence) => {
    expect(sentence).to.contain(cityName.trim())
  })
})

示例验证场景

期望内容:'Berlin in top 20 cities in the world for 2023! '
实际获取的城市文本:Berlin

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:50:41