模拟节点获取时出现"正文已用于"错误?



我正在尝试为我的azure函数使用jest模拟节点获取。在测试中,我有以下内容:

index.test.ts

jest.mock("node-fetch");
import fetch from "node-fetch";
const {Response} = jest.requireActual("node-fetch");
// Setup code here...
const expectedResult: User = {
user_id: "1",
email: "testEmail@email.com",
name: "testUser",
nickname: "test",
picture: "pic",
app_metadata: {
email: "testEmail@email.com"
}
};
(fetch as jest.MockedFunction<typeof fetch>).mockReturnValue(new Response(JSON.stringify(expectedResult)));

当我称之为时,我正在做以下事情:

index.ts


const options = {
method: 'PATCH',
headers: { "Content-Type": 'application/json', authorization: `Bearer ${accessToken}`},
body: body
};
const userResponse = await fetch(usersEndpoint, options);
const jsonResult = await userResponse.json();
context.res = {
body: jsonResult
};

当它击中";wait userResponse.json(("我得到了";身体已经用于";错误我有另一个以类似方式设置的测试,它可以工作,所以我不确定为什么它说等待获取调用的主体已经用完了。如有任何帮助,我们将不胜感激。

Response对象应该每个请求使用一次,而模拟fetch为多个请求返回相同的对象。此外,它应该返回一个响应的承诺,而不是响应本身。

嘲笑它的正确方法是:

fetch.mockImplementation(() => Promise.resolve(
new Response(JSON.stringify(expectedResult))
));

没有必要使用Response并遵循它所施加的限制,特别是因为Node中没有本机Response

它可以是:

fetch.mockResolvedValue({
json: jest.fn(() => expectedResult)
});

我的问题是,我调用了另一个使用fetch的函数,该函数正在解决我的mock实现。我曾经嘲笑过这个回报值:

(fetch as jest.MockedFunction<typeof fetch>).mockReturnValue(new Response(JSON.stringify(expectedResult)));

最后工作了。

@埃斯图斯·弗拉斯克的回答最终也起了作用。

最新更新