如何获取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
相关产品推荐
相关产品推荐

