Javascript Jest-TypeError:response.json不是函数
我们正在使用Jest对React本机应用程序进行单元测试,Jest使用fetch进行各种API调用 为了测试API调用函数,我们已经模拟了获取API调用函数的调用。到目前为止,这种方法效果良好。我们还有一些函数将这些API调用结合起来,并对它们进行一些逻辑操作 例如,这里有一个函数,给定一个令牌,它将获取相关用户的第一个项目[0],并返回此项目中的项目列表Javascript Jest-TypeError:response.json不是函数,javascript,json,react-native,jestjs,fetch-api,Javascript,Json,React Native,Jestjs,Fetch Api,我们正在使用Jest对React本机应用程序进行单元测试,Jest使用fetch进行各种API调用 为了测试API调用函数,我们已经模拟了获取API调用函数的调用。到目前为止,这种方法效果良好。我们还有一些函数将这些API调用结合起来,并对它们进行一些逻辑操作 例如,这里有一个函数,给定一个令牌,它将获取相关用户的第一个项目[0],并返回此项目中的项目列表 export async function getAllItems(token) { try { const response
export async function getAllItems(token) {
try {
const response = await getCurrentUser(token); // fetch called inside
const responseJson = await response.json();
const allItemsResp = await getAllItemsFromSpecificProject(
token,
responseJson.projectIds[0],
); // fetch called inside
return await allItemsResp.json();
} catch (error) {
console.log(error);
return null;
}
}
getCurrentUser和getAllItemsFromSpecificProject这两个函数都是简单的获取调用,并且当前被正确模拟。这里有一个测试尝试测试getAllItems函数:
it('Gets all items', async () => {
getAccessTokenMockFetch();
const token = await getAccessToken('usherbrooke@powertree.io', 'test!23');
getAllItemsMockFetch();
const items = await getAllItems(token.response.access_token);
expect(items.response.length).toEqual(3);
});
为了清楚起见,下面是如何完成getAccessTokenMockFetch的。getAllItemsMockFetch与响应中的不同数据几乎相同:
function getAccessTokenMockFetch() {
global.fetch = jest.fn().mockImplementation(() => {
promise = new Promise((resolve, reject) => {
resolve(accepted);
});
return promise;
});
}
其中accepted包含成功调用的JSON内容。运行此测试时,会出现以下错误:
TypeError: Cannot read property 'response' of null
我们将console.log记录在catch中:
TypeError: response.json is not a function
这解释了为什么响应为空。json调用似乎不被理解,我不知道如何模拟它。我对堆栈溢出和其他问题做了大量的研究,但我们没有发现任何东西可以帮助我理解如何解决这个问题。这可能表明我在这方面走错了方向,这是很有可能的,因为我不熟悉JavaScript、React Native和Jest。尝试的一件事是给它一个假json来调用,如下所示:
const mockFetch = Promise.resolve({ json: () => Promise.resolve(accepted) });
global.fetch = jest.fn().mockImplementation(() => mockFetchPromise);
在本例中,我只从mockImplementation获取解析中传递的数据,我希望从真实api获取响应,并测试该响应,如果获取api中所有必需的项,我如何使用fetch实现@艾米丽·科尔曼