gpt4 book ai didi

javascript - 模拟 Node 获取时出现“已使用的主体”错误?

转载 作者:行者123 更新时间:2023-12-05 00:38:27 24 4
gpt4 key购买 nike

我正在尝试用我的天蓝色函数来模拟 Node 获取。在测试中,我有以下内容:
索引.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)));

当我调用它时,我正在执行以下操作:
索引.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
};

当它遇到“等待 userResponse.json()”时,我得到“body used already for”错误。我有另一个以类似方式设置的测试,它有效,所以我不确定为什么它说 body 从 await fetch 调用中用完。任何帮助,将不胜感激。

最佳答案

响应对象应该在模拟时每个请求使用一次 fetch为多个请求返回相同的对象。此外,它应该返回一个响应的 promise ,而不是响应本身。
模拟它的正确方法是:

fetch.mockImplementation(() => {
return Promise.resolve(new Response(JSON.stringify(expectedResult)))
});
没有必要使用 Response并遵守它施加的限制,特别是因为没有原生 Response在 Node 。
有可能:
fetch.mockResolvedValue({
json: jest.fn().mockResolvedValue(expectedResult)
});

关于javascript - 模拟 Node 获取时出现“已使用的主体”错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63155034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com