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

如何用TypeScript、Jest和Axios在同一单元测试中模拟两个不同请求?

嵌套函数双GET请求的测试模拟方案

方案1:按调用顺序返回不同响应

如果functionA和内部的functionB发起请求的顺序固定,可以用mockResolvedValueOnce分别指定两次请求的响应结果:

it("test", async () => {
    // 第一个请求(functionA发起的GET)的响应
    mock.get.mockResolvedValueOnce({ data: RESPONSE_A });
    // 第二个请求(functionB发起的GET)的响应
    mock.get.mockResolvedValueOnce({ data: RESPONSE_B });

    const response = await functionA(input);

    expect(response).toMatchObject({ status: 1 });
    // 根据实际业务逻辑调整断言,比如如果响应包含两个请求的结果,对应修改
    expect(response.value).toMatchObject({
      state: { status: "OK" },
      data: RESPONSE_A,
      bData: RESPONSE_B // 假设functionB的结果会被包含在这里
    });
    // 验证mock被调用了两次
    expect(mock.get).toHaveBeenCalledTimes(2);
  });

方案2:按请求端点动态返回响应

如果请求顺序不固定,或者需要精准匹配不同的接口端点,可以给mock函数添加逻辑,根据传入的URL返回对应响应:

it("test", async () => {
    mock.get.mockImplementation((url) => {
        // 替换成实际的两个请求端点
        if (url === "/api/functionA-endpoint") {
            return Promise.resolve({ data: RESPONSE_A });
        } else if (url === "/api/functionB-endpoint") {
            return Promise.resolve({ data: RESPONSE_B });
        }
        // 可选:处理未匹配的请求
        return Promise.reject(new Error("Unknown API endpoint"));
    });

    const response = await functionA(input);

    expect(response).toMatchObject({ status: 1 });
    // 验证mock调用次数和对应的URL
    expect(mock.get).toHaveBeenCalledTimes(2);
    expect(mock.get).toHaveBeenCalledWith("/api/functionA-endpoint");
    expect(mock.get).toHaveBeenCalledWith("/api/functionB-endpoint");
  });

关键注意点

  • 确保你使用的测试框架(比如Jest)支持mockResolvedValueOnce和mockImplementation这类mock方法。
  • 要确认两个请求的端点URL或者调用顺序的准确性,否则mock无法正确匹配对应的请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:54:55