简体   繁体   English

我可以在功能组件上使用 jest/rtl 模拟 ref 属性吗?

[英]Can I mock a ref property using jest/rtl on a functional component?

I currently have a functional component with a helper function我目前有一个带有辅助功能的功能组件

function Component() {
    imgRef = useRef(null)     

    function helperFunction(node, ref) { 
        if (!ref || !ref.current) return; 
        ...do something    
    }     

    return (
       <Component onAlign={(node) => {helperFunction(node, imgRef)}>
           <img ref={imgRef} />
       </Component>
    )
}

And I can't seem to cover the edge case而且我似乎无法涵盖边缘情况

if (!ref || !ref.current) return;

I've tried mocking the useRef to return null but it hasn't worked.我尝试模拟 useRef 以返回 null,但它没有奏效。 Is there a way I would be able to test this or mock the ref property of the to null?有没有办法可以测试这个或将 ref 属性模拟为 null ?

With RTL you can´t!使用 RTL,您不能! As you can check on faq :您可以查看常见问题解答

Help!帮助! I can't access component methods or the component instance!我无法访问组件方法或组件实例! This is intentional.这是故意的。

We want you to focus on testing the output and functionality of the component as it is observed by the user and to avoid worrying about the implementation details of the component.我们希望您专注于测试用户观察到的组件的输出和功能,并避免担心组件的实现细节。

We believe this leads to less brittle and more meaningful test code.我们相信这会导致更少的脆弱性和更有意义的测试代码。

Testing-library also have some guiding principles that you can check here . Testing-library也有一些指导原则,您可以在此处查看

And complementing the answer, Is there any chance that ref will be null when helperFunction is called?并补充答案,当helperFunction时,是否有可能ref为空? Checking your code over i believe its not possible as you are explicit setting <img ref={imgRef} /> .检查您的代码我相信这是不可能的,因为您明确设置<img ref={imgRef} /> So maybe you just dont need this verification.所以也许你只是不需要这个验证。

* Related to Jest, maybe you can force some mock on the Component. * 与 Jest 相关,也许您可​​以在组件上强制进行一些模拟。 But again, you will be going against Guiding Principles from RTL.但是,您将再次违反 RTL 的指导原则。

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

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