使用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
相关产品推荐
相关产品推荐

