DEV Community

lshawa
lshawa

Posted on

How do we unit test functions within a functional component?

With a class component I usually create an instance of that component and I can access the function. I'm not sure how to access the function of a functional component.

const errorMessages = {
    browse: {
        fileLimit: 'File size is too big.',
        unsupportedFormat: 'The file you selected is not a supported format. Please upload a file in .csv format.',
        noRows: 'No agent IDS could be found.',
        maxAgents: 'A max of 25 agents can be uploaded at a time.',
        noValidAgents: 'No valid agents could be found.'
    },
    duplicate: 'The following agents are already existing on the table.'
};
Enter fullscreen mode Exit fullscreen mode

const UploadButton = (props, ref) => {
const mimeTypes = ['text/csv', 'application/vnd.ms-excel'];
let initialValue = false;
const [browseError, setBrowseError] = useState(initialValue);
const [uploadError, setUploadError] = useState(initialValue);
const [duplicateError, setDupplicateError] = useState(initialValue);
const [uploading, setUploading] = useState(false);
const fileInputRefs = useRef(initialValue);

const clearAllErrors = () => {
    setBrowseError(initialValue);
    setUploadError(initialValue);
    setDupplicateError(initialValue);
}
Enter fullscreen mode Exit fullscreen mode

....
}

So accessing clearAllErrors for example or errorMessages which outside of the functional component.

Top comments (2)

Collapse
 
joerter profile image
John Oerter

Instead of testing the function off of the component, I would recommend asserting against the rendered component. I recommend taking a look at react-testing-library and adopting it's approach to writing unit tests. I've been really happy with it in general.

Collapse
 
matenemeth profile image
Matt Nemeth • Edited

This^ . Also, if you have a function you reeeeally need to test, you can always extract it into a separate file/module/service/whatever, and you can unit test it separately from the functional component.