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

Cypress中两次调用invoke()方法报错找不到attr属性问题求助

问题原因说明

两次invoke的调用顺序本身没有逻辑问题,报错是由Cypress的链式调用规则和错误的变量复用方式导致的:

  • Cypress的命令是链式传递主体的:第一次执行sty.invoke("attr", "style")是读取元素的style属性,执行完成后链式传递的主体会从原来的DOM元素变为读取到的style字符串,复用提前赋值的sty变量执行第二次invoke时,实际是在字符串对象上调用不存在的attr方法,因此触发报错。
  • 将cy.get()的结果提前赋值给opt、sty变量的写法不符合Cypress最佳实践,Cypress命令返回的是异步链式对象,不是实际的DOM元素实例,复用变量很容易出现主体错位的问题。
解决方案

你可以选择任意一种方案修复问题:

方案1:每次操作重新查询元素(写法最简单)

避免复用提前定义的元素查询变量,每次操作前重新查询目标元素,确保操作主体始终是DOM元素:

describe('My first test', function(){
    beforeEach(() => {
        cy.visit("https://www.wikiwand.com/en/IPv4")
    })
    it('test1', function() {
        cy.get("#main_menu > li").eq(3).click()
        // 第一次校验初始值
        cy.get(".noUi-origin").first().invoke("attr", "style").should("include", "left: 0%;")
        // 第二次重新查询元素后设置属性并校验
        cy.get(".noUi-origin").first().invoke("attr", "style", "left: 100%;").should("have.attr", "style", "left: 100%;")
    })
})

方案2:用then持有元素实例(避免重复查询)

如果你不想重复查询元素,可以用then方法获取到实际的JQuery元素实例后再执行两次操作:

describe('My first test', function(){
    beforeEach(() => {
        cy.visit("https://www.wikiwand.com/en/IPv4")
    })
    it('test1', function() {
        cy.get("#main_menu > li").eq(3).click()
        cy.get(".noUi-origin").first().then($origin => {
            // 基于同一个元素实例执行两次操作
            cy.wrap($origin).invoke("attr", "style").should("include", "left: 0%;")
            cy.wrap($origin).invoke("attr", "style", "left: 100%;").should("have.attr", "style", "left: 100%;")
        })
    })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:15:02