如何验证TotalMessageUI_ObjectClicked非空非0?Cypress断言报错求助
问题描述
我想要验证TotalMessageUI_ObjectClicked的值不为NULL或0,但运行Cypress断言时持续报错:
AssertionError: expected [ { payload: { data: [Object] } } ] to have property 'TotalMessageUI_ObjectClicked'
提供的响应数据结构:
{"data":{"actor":{"account":{"nrql":{"results":[{"TotalMessageUI_ObjectClicked":6}]}}}}}
我尝试的断言代码:
expect(response.body).have.property('TotalMessageUI_ObjectClicked').to.not.be.oneOf([null, "",0])
解决方法
报错核心是断言路径错误,TotalMessageUI_ObjectClicked并非直接挂载在response.body下,而是嵌套在多层对象和数组中,正确路径为response.body.data.actor.account.nrql.results[0].TotalMessageUI_ObjectClicked。以下是几种可靠的验证方式:
方式1:直接取值后断言
const targetValue = response.body.data.actor.account.nrql.results[0].TotalMessageUI_ObjectClicked; expect(targetValue).to.not.be.oneOf([null, "", 0]);
方式2:Cypress链式断言(更贴合框架风格)
cy.wrap(response.body.data.actor.account.nrql.results[0]) .should('have.property', 'TotalMessageUI_ObjectClicked') .and('not.be.oneOf', [null, "", 0]);
方式3:兼容数组为空的健壮写法
如果results数组可能为空,建议先校验数组长度避免报错:
expect(response.body.data.actor.account.nrql.results).to.have.length.greaterThan(0); const targetValue = response.body.data.actor.account.nrql.results[0].TotalMessageUI_ObjectClicked; expect(targetValue).to.not.be.oneOf([null, "", 0]);
内容的提问来源于stack exchange,提问作者testerJeff
相关产品推荐
相关产品推荐

