我试图用笑话来模仿我的azure函数中的node-fetch。 在测试中,我有以下内容:
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)));
当我调用它时,我正在做以下工作:
索引。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
};
当它到达“await userresponse.json()”时,我会得到“body used agement for”错误。 我有另一个测试,它是以类似的方式设置的,它的工作方式,所以我不确定为什么它说身体是用完了从await fetch调用。 如有任何帮助,我们将不胜感激。
响应对象应该在每个请求中使用一次,而mockedfetch
则为多个请求返回相同的对象。 此外,它应该返回一个响应的承诺,而不是响应本身。
嘲笑它的正确方法是:
fetch.mockImplementation(() => {
return Promise.resolve(new Response(JSON.stringify(expectedResult)))
});
没有必要使用response
并遵循它施加的限制,特别是因为Node中没有本机response
。
它可以是:
fetch.mockResolvedValue({
json: jest.fn().mockResolvedValue(expectedResult)
});
我的问题是我调用了另一个函数,该函数使用fetch来解析我的模拟实现。 有一次我嘲笑那个返回值:
(fetch as jest.MockedFunction<typeof fetch>).mockReturnValue(new Response(JSON.stringify(expectedResult)));
最后工作了。
@Estus Flask的回答也最终奏效。