繁体   English   中英

如何在 jest 和 @testing-library/react 中测试 catch 部分

[英]How to test catch part in jest and @testing-library/react

我的组件.js

<Button
    onClick={ async e =>{
    resetForm();
    }}
    Reset
</Button>


const resetForm= () => {
    try{
        someRef.current.resetFormValues();
        const div = document.getElementById("errorDisplayDiv");
        div.innerHTML="";
        div.style.display = "none";
        setSomeVaribale();
    }
    catch(error){
        setStateAndLogError(error);
    }
}

我无法涵盖测试用例中的捕获部分。 我正在使用jest: 24.9.0 和 @testing-library/react: 12.1.2

编辑:对不起,我误读了你的问题。

为此,您需要模拟文档 object 并让它抛出错误。 在您的测试中,一种方法可能是这样的:

global.document = { 
  getElementById: () => throw new Error('fake error')
}

现在调用该方法将抛出并退回到您的测试中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM