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

如何获取jest.spyOn监听方法的返回值并校验数组长度?

解决方法

当然有办法捕获返回值,Jest的mock函数本身就会记录所有调用的返回结果,直接用它提供的属性就能拿到实际返回内容:

  • 获取最后一次调用的返回值:用myfunc.mock.lastReturnValue直接拿到最近一次调用的返回对象,接着就能校验数组长度:

    const myfunc = jest.spyOn(someLibrary, 'yourTargetMethod');
    
    // 执行触发该方法的业务代码
    yourTestedFunction();
    
    // 校验返回数组的长度
    expect(myfunc.mock.lastReturnValue.length).toBe(3);
    
  • 获取某次特定调用的返回值:如果方法被调用多次,myfunc.mock.results是一个数组,每个元素包含对应调用的返回信息,通过索引取对应值:

    // 获取第一次调用的返回值
    const firstReturn = myfunc.mock.results[0].value;
    expect(firstReturn.length).toBe(5);
    
    // 获取第二次调用的返回值
    const secondReturn = myfunc.mock.results[1].value;
    expect(secondReturn.length).toBe(2);
    
  • 手动拦截记录返回值:如果需要更灵活的控制,可以在mockImplementation里包裹原方法,同时保存返回值:

    let capturedResult;
    const myfunc = jest.spyOn(someLibrary, 'yourTargetMethod')
      .mockImplementation((...args) => {
        // 调用原方法拿到结果
        const result = someLibrary.yourTargetMethod(...args);
        // 保存结果
        capturedResult = result;
        return result;
      });
    
    yourTestedFunction();
    expect(capturedResult.length).toBe(4);
    

注意:用完spy之后记得在测试结束后调用myfunc.mockRestore()清除mock,避免影响其他测试用例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:27:28