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

Jest单元测试soap.createClientAsync返回方法执行失败问题

报错根因

mock soap.createClientAsync 时返回值写错了:
你当前的mock逻辑是让createClientAsync返回一个函数,该函数执行后才会resolve出构造的client对象。但业务代码里是直接await soap.createClientAsync(flavourUrl)接收返回值,最终拿到的client是你返回的那个空函数,不是带RegisterExperimentAsync方法的mock对象,自然会触发「方法不存在」的报错。
另外你没有给RegisterExperimentAsync这个mock方法配置返回值,就算修复上面的问题,最终拿到的执行结果也会是undefined,无法通过断言。

修复后的测试用例代码
describe("**** Register via soap service ****", () => {
  it("** should excecute register method **", async () => {
    const request = cloneDeep(MOCK.API_PAYLOAD);
    // 构造mock返回值
    const mockResponse = { Result: AFB_MOCK_RESPONSE.API_RESPONSE };
    const mockClient = {
      RegisterExperimentAsync: jest.fn().mockResolvedValue(mockResponse)
    };
    // 修正mock:createClientAsync本身返回Promise,直接resolve成mockClient即可,不要多包一层函数
    jest.spyOn<any, any>(soap, "createClientAsync").mockResolvedValueOnce(mockClient);

    // 注意:registerInSoap是类的实例方法,需要先实例化再调用,如果是静态方法请给方法加static修饰符
    const soapHelperInstance = new soapHelper();
    const result = await soapHelperInstance.registerInSoap(request);
    
    expect(result).toEqual(mockResponse);
    // 可选:校验调用参数是否符合预期
    expect(mockClient.RegisterExperimentAsync).toHaveBeenCalledWith({ upload: request });
  });
});
其他需要留意的代码问题
  • 业务代码registerInSoap方法内定义的地址变量叫url,实际传给createClientAsync的参数是flavourUrl,如果不是笔误会触发变量未定义的运行时错误。
  • 测试用例执行完记得恢复soap.createClientAsync的mock,避免影响其他测试用例,可以在afterEach里加jest.restoreAllMocks()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:57:19