javascript - 如何模拟在同一函数中进行的多个 fetch 调用
问题描述
我有一个函数,如下所示,它在同一个函数中执行 2 个 fetch 调用
getNames() {
var qs = require("qs");
fetch(<URL>,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: qs.stringify({
firstName: this.state.firstName,
lastName: this.state.lastName
})
})
.then(response => response.json()).then((data) => {
console.log(data)
});
var url = new URL(<someURL>)
fetch(<someURL>).then(response => response.json()).then((data) => {
...do something...
}
})
.catch(error => {
alert("no response");
console.log(error);
});
}
我正在使用 Jest 和 Enzyme on React 对此进行测试。以上属于 GetName 组件。下面是我的测试用例:
describe('getName', () => {
const wrapper = shallow(<GetName />).instance();
beforeEach(() => {
global.fetch.resetMocks();
});
it('positive flow', () => {
global.fetch.mockResolvedValue(
new Response(JSON.stringify({data: "mockData"}))
);
const state = {
firstName: "don",
lastName: "Lee"
};
wrapper.setState(state);
const actualValue = wrapper.getNames();
expect(actualValue).toBeUndefined();
});
});
一旦我这样做,我会收到一个错误TypeError: body used already for: undefined
我知道这里的 fetch 用于 POST 调用,但是我如何确保我可以在函数中模拟两个 fetch 调用?
我也试过fetch.mockResponse
and fetch.mockResponses
and also fetch.mockResponseOnce
。它们似乎都没有帮助我不止一次地模拟它们,并且提到的所有功能都出现了这个错误。
有没有其他方法可以模拟两个 fetch 调用?
解决方案
推荐阅读
- javascript - 以 Outlook 格式解析电子邮件
- xml - XSLT XPath:如果更新了一个子节点,则从不同的子节点(对于同一个工作人员)获取数据-如何处理?
- javascript - 无法检测到触摸拖放事件
- snort - 防止恶意文件下载的 Snort 规则
- linux - 如何在 CircleCI 中更新 /etc/hosts?
- c - C 中 float 与 long 的结果差异
- node.js - 如何在 Windows 10 Home 上安装 node.js?
- ethereum - 如何在 MetaMask 上触发更改区块链网络请求
- php - Url Manager 无限循环,刷新页面
- javascript - TypeError:此条件将始终返回 'false',因为类型 '"id"' 和 '"en"' 没有重叠