首页 > 解决方案 > 笑话。测试在一个函数中执行 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)
    }
};

标签: javascriptnode.jsexpresswebpackjestjs

解决方案


推荐阅读