javascript - 笑话。测试在一个函数中执行 POST 和 fetch 的异步函数
问题描述
我需要使用 jest 来测试一个包含两个函数的函数。我尝试测试的函数中的第一个函数将 POST 发送到其中包含 API 调用的路由,第二个函数从我设置的服务器上的端点获取从 API 返回的数据。我对 jest 以及使用 jest 的哪些部分来测试此功能知之甚少。我是否将两个测试嵌套在一个主要功能的测试中?这些是我需要测试的功能:
handleSubmit(我需要测试的主要功能):
document.getElementById('generate').addEventListener('click', handleSubmit);
function handleSubmit(event) {
//event.preventDefault()
// check what text was put into the form field
let url = document.getElementById('URL').value
postURL('/postURL', url)
.then(updateUI())
.then(checkURL)
};
postURL(嵌套在主函数中的第一个函数,使 POST)
let postURL = async(url = '', data = {})=>{
console.log(data);
let response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
"Content-Type": 'application/json',
},
body: JSON.stringify( { data} ),
});
try {
updateUI()
}catch(error){
console.log("error", error);
}
}
updateUI(获取数据的第二个函数):
const updateUI = async () =>{
const res = await fetch('/sentiment');
console.log(res);
try {
console.log(res.data)
const allData = await res.json();
console.log(allData)
document.getElementById("polarity").innerHTML = allData.polarity;
document.getElementById("polarityConfidence").innerHTML = allData.polarity_confidence;
document.getElementById("subjectivity").innerHTML = allData.polarity;
document.getElementById("subjectivityConfidence").innerHTML = allData.polarity_confidence;
return allData;
}catch(error){
console.log(error)
}
};
解决方案
推荐阅读
- python - 为调度程序使用堆
- r - 为什么逐步计算 mse 不会产生与 MSE 函数相同的解决方案?
- java - 无法在 spring-boot 中使用 maximumSessions 和 maxSessionsPreventsLogin 设置并发会话控制
- c# - 是否有可能在 c# 中处理更高精度的复杂数据类型?
- php - 在 PHP 中将 SAML 身份映射到我自己的数据库中的用户
- python - Firestore 无法获取路径快照
- java - 如何在 Lambda 表达式中定义 Intent
- python - 数据框无法填充熊猫中的 NaN 值
- ruby - 使用 gem 时 main:Object 的未定义方法错误
- java - Java 在读取文件但同时使用流时避免 java.lang.OutOfMemoryError