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

Cypress中AssertionError问题:别名显示为[object Object]如何解决?

问题分析与修正

你遇到的[object Object]错误,是因为cy.get('@totalPriceInCart')是Cypress的命令对象,并非实际的总价数值,直接拼接字符串会输出对象的默认toString结果。另外原代码里text变量未定义,也是需要修正的点。

修正方案一:通过.then()获取别名值

把校验逻辑嵌套到cy.get('@totalPriceInCart')的回调中,拿到真实数值后再执行断言:

cy.get('.lead').should('be.visible').then((domElementWithText) => {
  const text = domElementWithText.text(); // 获取确认文本内容
  cy.get('@totalPriceInCart').then(totalPrice => {
    expect(text).to.include(`Amount: ${totalPrice} USD`);
  });
});

修正方案二:使用this访问别名值

改用普通函数(不能用箭头函数),可以通过this.totalPriceInCart直接获取别名存储的数值:

cy.get('.lead').should('be.visible').then(function(domElementWithText) {
  const text = domElementWithText.text();
  expect(text).to.include(`Amount: ${this.totalPriceInCart} USD`);
});

补充说明

  • 你保存别名的代码是正确的:cy.get("#totalp").invoke('text').then(parseInt).as('totalPriceInCart');,已经将文本转换为整数类型的总价。
  • 两种方案均可解决断言错误,方案二更简洁,可根据编码习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:42:44