reactjs - 如何使用 jest 和酶在 reactJs 中构建测试用例以使用 fetch 调用进行测试
问题描述
我有以下代码
getFullName() {
var urlendPoint = new URL(propertiesInFile.urltoPing)
var params = {
firstName: this.state.firstName,
lastName: this.state.lastName
}
urlendPoint.search = new URLSearchParams(params)
fetch(urlendPoint).then(response => response.json()).then((data) => {
...perform some actions...
}
})
.catch(error => {
alert("Please check the names and try again");
});
}
propertiesInFile 只是我在另一个 js 文件中定义的硬编码值。
在上面的代码中,我似乎无法模拟 fetch 调用。我如何在反应中测试这个函数,以便我可以获得函数中的状态(名字和姓氏),覆盖 catch 块并尝试到位的 fetch 调用。
解决方案
在您的测试中,您可以将 fetch 分配给类似这样的模拟函数
global.fetch = jest.fn().mockImplementation(() => mockFetchPromise);
您可以在此网站上找到更多详细信息
推荐阅读
- java - 增强了字符串的 for 循环
- c# - 异步 Lambda 函数
- date - 为什么这个 INSERT 查询会插入一个时间值,而不是一个日期?
- android - can we inherit `style_one.style_two.style_three` with having `style_one` and no `style_one.style_two` in android style?
- aws-lambda - 获取 Redshift 中的所有表名
- django - When trying to install JWT package for Django getting error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
- controller - How can I empty a request on Laravel Controller?
- c - 假定会导致总线错误的代码块执行得很好
- r - ggplot中的叠瓦轴
- c# - Edit requiredResourceAccess of Azure AD Application using MVC or C#.NET application