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

Cypress跨步骤共享alias别名返回undefined问题求助

问题核心原因

你的写法有两个核心错误:

  • 你没有正确理解Cypress命令的异步执行逻辑:cy.get("@storedOddsValue")返回的是Cypress内部的链式命令对象,不是你之前存储的实际字符串值,你直接把这个对象传给oddslib.from方法自然无法正常转换。
  • 你在第一个步骤的then回调中没有返回trim处理后的赔率值,最终as存储的别名内容是未处理的原始文本,就算能拿到值也可能因为前后空格导致匹配失败。
修复方案

第一步:修正别名存储逻辑

修改第一个Then步骤的代码,在then回调中返回trim后的有效值,确保别名存储的是你需要的正确内容:

Then ("The prices are formatted in fractions by default", () => {
    priceFormatElements.priceFormatDropdown().should('have.value', 'Fraction');
    oddsSelectionElements.oddsButton().first().invoke("text")
    .then((oddsValue) => {
        const trimmedOdds = oddsValue.trim();
        expect(trimmedOdds).contains("/");
        return trimmedOdds; // 必须return处理后的值,才能传递给后续的as存储
    }).as("storedOddsValue")
})

第二步:修正别名取值逻辑

所有依赖别名值的逻辑必须放在cy.get("@storedOddsValue")的then回调中执行,确保你拿到的是实际存储的字符串值之后再做后续处理:

Then ("The prices are formatted in {string}", (priceFormat) => {
    // 先通过then拿到别名的实际值
    cy.get("@storedOddsValue").then(storedOddsStr => {
        const storedOddsValue = oddslib.from("fractional", storedOddsStr);
        let expectedOddsValue;

        switch (priceFormat) {
            case "Fractional":
              expectedOddsValue = storedOddsValue.to("fractional");
              break;
            case "Decimal":
              expectedOddsValue = storedOddsValue.to("decimal", {precision: 2});
              break;
            case "American":
              expectedOddsValue = "+" + storedOddsValue.to("moneyline");  
              break;
            default:
              throw new Error('unknown price format: ' + priceFormat);
        }

        // 拿当前赔率值做断言
        oddsSelectionElements.oddsButton().first().invoke("text")
        .then((currentOdds) => {
            expect(currentOdds.trim()).equals(expectedOddsValue);
        });
    })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:54:01