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

如何在MyCustomClass.js加载完成后立即Stub其myMethod方法?

解决方法

当前的问题是cy.wait()的回调属于异步执行逻辑,页面在MyCustomClass加载完成后会立刻调用myMethod,导致Stub还没生效就使用了原始返回值。要在类加载后立刻完成Stub,得从请求拦截的生命周期入手,提前介入处理:

方案1:修改响应脚本,直接注入Stub

直接在返回的MyCustomClass脚本末尾追加Stub代码,类定义完成后自动生效:

cy.intercept("GET", "http://127.0.0.1:9002/services/managers/MyCustomClass.js", (req) => {
  req.continue((res) => {
    // 在原脚本末尾追加Stub逻辑
    res.body += `
      window.MyCustomClass.myMethod = () => '123';
      console.log('Stub injected immediately after class load');
    `;
    return res;
  }).as("loadMyCustomClass");
});

cy.visit("index.html");

浏览器执行修改后的脚本时,类刚定义完成就会执行我们添加的Stub代码,完全赶在页面调用myMethod之前生效。

方案2:用intercept的响应事件同步Stub

如果不想修改原脚本,可利用拦截器的onResponse回调——这个回调会在请求完成后立刻触发,比cy.wait()的回调时机更早:

cy.intercept("GET", "http://127.0.0.1:9002/services/managers/MyCustomClass.js")
  .as("loadMyCustomClass")
  .on("response", () => {
    cy.window().then((win) => {
      cy.stub(win.MyCustomClass, "myMethod").returns("123");
      console.log("MyCustomClass.myMethod stubbed");
    });
  });

cy.visit("index.html");

原代码失效原因

原代码中cy.wait().then()是把Stub逻辑放进了Cypress的异步任务队列,而页面在MyCustomClass加载完成后会同步调用myMethod,此时Stub还未执行,自然会使用原始返回值。上面两个方案都是在请求生命周期的更早阶段处理,确保Stub先于方法调用生效。

验证方式

在MyCustomClass.ts末尾添加一行测试代码:

console.log('myMethod result:', MyCustomClass.myMethod());

如果Stub生效,控制台会输出myMethod result: 123,而非原始的MyCustomClass myMethod value。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:41:14