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

使用Jest+Mockfetch测试Unsplash API时遇JSON输入异常如何解决?

解决Jest测试Mock fetch时的JSON解析错误

问题出在你当前的测试只验证了fetch被调用,但没有给Mock的fetch设置有效的返回响应。当测试执行到response.json()时,因为Mock响应没有提供可解析的JSON内容,所以抛出了Unexpected end of JSON input错误。

修复步骤

  • 在测试中给Mock的fetch设置返回值,让它返回一个包含json()方法的响应对象,该方法返回符合Unsplash API格式的模拟JSON数据。
  • 可以通过jest.spyOn来Mock全局的fetch,并指定返回值。

修改后的测试代码示例

test('it makes a fetch call to unsplash and returns data', async () => {
    // 模拟Unsplash API返回的照片数据结构
    const mockPhotoData = {
        id: 'test-photo-id',
        urls: { regular: 'https://example.com/test-image.jpg' }
    };
    
    // Mock fetch的返回响应
    const mockResponse = {
        json: jest.fn().mockResolvedValue(mockPhotoData)
    };
    global.fetch = jest.fn().mockResolvedValue(mockResponse);

    const result = await api.fetchPhoto('wedding');
    
    // 验证fetch被调用的参数是否正确
    expect(fetch).toHaveBeenCalledWith(
        'https://api.unsplash.com/photos/random?query=wedding&per_page=1&client_id=gKEeCzK-8XXRBG8IHbYAGTEUDMN-Dpm9FjxjDS4f2Y0'
    );
    // 验证返回的数据与模拟数据一致
    expect(result).toEqual(mockPhotoData);
    // 验证json()方法被正确调用
    expect(mockResponse.json).toHaveBeenCalled();
})

额外注意事项

  • 如果你的项目使用jest-fetch-mock库,可以简化Mock逻辑:在测试开头执行global.fetch = require('jest-fetch-mock'),然后用fetch.mockResponse(JSON.stringify(mockPhotoData))直接设置响应内容。
  • 若需要测试错误场景(比如请求失败),可以设置Mock响应的ok属性为false,模拟非成功状态码的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:21:10