Unit testing functional component functions in React

Gemini generated image omip4xomip4xomip

Say you have a functional component like this :

const myComponent = () => { 
 const myFunction = () => {
  // Do some stuff
 }
}

and you want to unit test the function myFunction. Since under functional components we can’t access functions within it directly and run it to perform tests, we end up depending on results of effects of the function to the whole component instead.

In cases where we want to run unit test for a specific function within a functional component what we can do is move our function outside of the component and export it. Like the following

export const myFunction => {
 // Do stuff ... 
}

const myComponent = () => {
 return .... 
}

this way we can still can myFunction inside the component while being able to run it on its own for testing.

You can also move it in a separate file to fit your organizational structure.

Then to unit test you can write something like this:

import {myFunction} from './mycomponent'

test('function works', () => {
 const result = myFunction()
 expect(result).toBe(true)
})

Unit testing functions separately helps minimize errors in the long run. You can also assure that correct output is returned based on various inputs.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *