我正在使用 Mockfest 来测试一个非常简单的 unsplash api。 当然,fetch 调用工作得很好,它看起来像这样:
test('it makes a fetch call to unsplash', async () => {
await api.fetchPhoto('wedding')
expect(fetch).toHaveBeenCalled()
})
从 Jest 脚本中可以看出:
● 它对 unsplash 进行 fetch 调用
FetchError: invalid json response body at reason: Unexpected end of JSON input
4 |
5 | const response = await fetch(url)
> 6 | const data = await response.json();
| ^
7 |
8 | return data;
9 | }
这是我的获取函数:
async function fetchPhoto (event) {
const url = 'https://api.unsplash.com/photos/random?query='+event+'&per_page=1&client_id=gKEeCzK-8XXRBG8IHbYAGTEUDMN-Dpm9FjxjDS4f2Y0';
const response = await fetch(url)
const data = await response.json();
return data;
}
module.exports = { fetchPhoto };
我怎样才能克服这个错误,我的意思是我的获取函数可以工作并返回 它应该返回什么。
response.json()
尝试将响应正文解析为 JSON,如 JSON.parse()
。
通常此错误意味着您收到的响应的 JSON 格式不正确。您可以通过
console.log()
检查它,并首先使用 response.text()
将正文解析为文本,以查看它的格式或问题是什么。