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

Cypress中if条件失效:两个JSON文件验证始终显示失败

JSON对象内容匹配却输出"fail"的解决方案

问题原因

你代码里用request === json比较两个JSON对象,在JavaScript中,对象属于引用类型,===运算符比较的是两个对象的内存引用地址,而非实际内容。哪怕两个对象的键值对完全一致,它们也是独立的内存对象,因此这个比较永远返回false,导致日志始终输出"fail"。

解决方法

以下是三种可行的修改方案,按推荐程度排序:

方案1:使用Cypress的深度相等断言(推荐)

利用Cypress内置的断言语法,直接验证两个对象深度相等,同时还能自动生成测试报告:

cy.get('.dataTable-custom').get('.w-40').eq(0).then((el) => {
  cy.writeFile('request-number.json', {
    request_number: el.text().trim() // 加trim()避免文本前后空格导致的不匹配
  })
})
cy.readFile('request-number.json').then((request) => {
  cy.readFile('application-details.json').then((json) => {
    expect(request).to.deep.equal(json) // 深度相等断言
    cy.log("success") // 断言通过才会执行到这里
  })
})

方案2:直接比较对象的具体属性

如果只需要验证特定属性值,直接比较对应属性更精准:

cy.get('.dataTable-custom').get('.w-40').eq(0).then((el) => {
  cy.writeFile('request-number.json', {
    request_number: el.text().trim()
  })
})
cy.readFile('request-number.json').then((request) => {
  cy.readFile('application-details.json').then((json) => {
    if (request.request_number === json.request_number) {
      cy.log("success")
    } else {
      cy.log("fail")
    }
  })
})

方案3:将对象转为字符串后比较

把两个对象转为JSON字符串,再用===比较字符串内容:

cy.get('.dataTable-custom').get('.w-40').eq(0).then((el) => {
  cy.writeFile('request-number.json', {
    request_number: el.text().trim()
  })
})
cy.readFile('request-number.json').then((request) => {
  cy.readFile('application-details.json').then((json) => {
    if (JSON.stringify(request) === JSON.stringify(json)) {
      cy.log("success")
    } else {
      cy.log("fail")
    }
  })
})

注意:这种方式对对象的键顺序敏感,如果两个对象键顺序不同,即使值相同也会返回false。

原始代码与文件参考

test.cy.js(原始)

cy.get('.dataTable-custom').get('.w-40').eq(0).then((el) => {
  cy.writeFile('request-number.json', {
    request_number: el.text()
  })
})
cy.readFile('request-number.json').then((request) => {
  expect(request).to.be.an('object')
  cy.log(request)
  cy.readFile('application-details.json').then((json) => {
    expect(json).to.be.an('object')
    cy.log(json)
    if (request === json) {
      cy.log("success")
    } else {
      cy.log("fail")
    }
  })
})

request-number.json

{
  "request_number": "ARS/0099/2023"
}

application-details.json

{
  "request_number": "ARS/0099/2023"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:42:39