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

在TypeScript中使用Jest模拟fetch返回响应的类型问题

如何在Jest中仅模拟Response的部分属性(无需全量实现)

我有一个调用fetch()并处理响应不同情况的函数,在使用Jest模拟全局fetch时遇到了TypeScript类型校验问题:我只需要用到response.ok和response.json(),但TypeScript要求必须实现Response类型的所有属性,不想逐个补全这些无关属性,该怎么处理?

我的原始代码

describe('steam data fetch function', () => {
    const fetchMock = jest.spyOn(global, 'fetch').mockImplementation(
        jest.fn(() =>
            Promise.resolve({
                ok: false,
                json: () => Promise.resolve({ data: 'empty' }),
            })
        ) as jest.Mock
    );

    // 测试用例
    test('handles invalid data correctly', () => {
        fetchMock.mockResolvedValueOnce({
            ok: false,
            json: () => Promise.resolve({ data: 'test1' }),
        }) as jest.Mock;

        // 断言逻辑...
    });
    // 更多测试用例,每个用例重新设置fetchMock.mockResolvedValueOnce
});

遇到的TypeScript错误

Argument of type '{ ok: false; json: () => Promise<{ data: string; }>; }' is not assignable to parameter of type 'Response | Promise<Response>'. Type '{ ok: false; json: () => Promise<{ data: string; }>; }' is missing the following properties from type 'Response': headers, redirected, status, statusText, and 9 more.ts(2345)

解决方案

通过双重类型断言as unknown as Response绕过TypeScript的全量属性校验,只提供需要的ok和json属性即可:

test('handles invalid data correctly', () => {
    fetchMock.mockResolvedValueOnce({
        ok: false,
        json: () => Promise.resolve({ data: 'test1' }),
    } as unknown as Response);

    // 断言逻辑...
});

注:虽然可以参考相关文档实现更严谨的Response模拟,但这个方案已经能满足当前测试需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:09:54