我在这里绝望地寻求帮助。我试图用Jest测试一个函数,但我被一件事卡住了。当我试图模拟fetch请求时,我得到了这个错误:
TypeError: Cannot read property 'json' of undefined
字符串
我想测试的函数是这样的:
export const updateUI = async () => {
const res = await fetch('/sentiment');
console.log(res);
try {
console.log(res.data);
const allData = await res.json();
console.log(allData);
document.getElementById("polarity").innerHTML = allData.polarity;
document.getElementById("polarityConfidence").innerHTML = allData.polarity_confidence;
document.getElementById("subjectivity").innerHTML = allData.polarity;
document.getElementById("subjectivityConfidence").innerHTML = allData.polarity_confidence;
return allData;
} catch (error) {
console.log('error');
}
};
型
我想做的测试是:
import "regenerator-runtime/runtime";
import "core-js/stable";
import "fetch-mock";
const fetchMock = require('fetch-mock');
fetchMock.config.sendAsJson = true; //I've tried with and without this part and I get the same error
import updateUI from './updateUI';
import { isIterable } from "core-js";
describe('updateUI', () => {
it('can fetch', async () => {
fetchMock.get('/sentiment', {polarity: 'polarity', polarity_confidence: 'polarity confidence', subjectivity: 'subjectivity', subjectivity_confidence: 'subjectivity confidence'});
const res = await updateUI('/sentiment');
const allData = await res.json();
expect(allData.polarity).toEqual('polarity');
expect(allData.polarity_confidence).toEqual('polarity confidence');
expect(allData.subjectivity).toEqual('subjectivity');
expect(allData.subjectivity_confidence).toEqual('subjectivity confidence');
});
});
型
我真的不知道该怎么办。为什么它不会得到json对象?是因为我的updateUI函数在函数的try{}部分调用了json对象吗?如果是这样,我该如何测试它?
2条答案
按热度按时间u0njafvf1#
我看到两个问题
const res = await updateUI('/sentiment');
,这并不重要,因为updateUI不接受任何参数。res.json()
,这将不起作用,因为从你的实际方法中,你只返回响应。在你的测试中,你不需要执行.json()
。这就是你得到undefined的原因,因为没有json函数。pw136qt22#
这就是我如何做到的。更多信息可以在codegrepper上找到
确保
Promise.resolve
使用得当,并且模拟数据和API数据具有相同的格式。字符串