ave*_*mia 9 javascript node.js typescript jestjs node-fetch
我正在尝试用 jest 来模拟我的 azure 函数的节点获取。在测试中我有以下内容:
索引.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)));
Run Code Online (Sandbox Code Playgroud)
当我调用它时,我正在执行以下操作:
索引.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
};
Run Code Online (Sandbox Code Playgroud)
当它点击“等待 userResponse.json()”时,我收到“主体已用于”错误。我有另一个以类似方式设置的测试,该测试有效,所以我不确定为什么它说主体已从等待获取调用中用完。任何帮助,将不胜感激。
响应对象应该在每个请求中使用一次,而模拟fetch则为多个请求返回相同的对象。此外,它应该返回响应的承诺,而不是响应本身。
模拟它的正确方法是:
fetch.mockImplementation(() => Promise.resolve(
new Response(JSON.stringify(expectedResult))
));
Run Code Online (Sandbox Code Playgroud)
没有必要使用和遵循它所施加的限制,特别是因为Node.js 中Response没有原生的。Response
有可能:
fetch.mockResolvedValue({
json: jest.fn(() => expectedResult)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16978 次 |
| 最近记录: |