简体   繁体   中英

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. Is there a way I would be able to test this or mock the ref property of the to null?

With RTL you can´t! 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 .

And complementing the answer, Is there any chance that ref will be null when helperFunction is called? Checking your code over i believe its not possible as you are explicit setting <img ref={imgRef} /> . So maybe you just dont need this verification.

* Related to Jest, maybe you can force some mock on the Component. But again, you will be going against Guiding Principles from RTL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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