Jest Unit Testing for Functional Components

Mohit Khandelwal
2 min readMay 24, 2021

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!

To start with Jest, try installing it using below commands, with supported libraries —

Save it as a dev dependency in your package.json, so that your production build is light weighted. Then, to run test add below script in package.json

“test”: “cross-env NODE_ENV=test jest — coverage — silent”,

To run test cases deleting and creating all new snapshots, use below command —

Then create a Component, for e.g. — Button.js

Then create a test file in test folderButton.test.js and start writing your test case, using below code —

In above code, first describe()our test Component. Then, a unit test can start with it() , which takes two parameter, first a string describing your test case and second a callback function expecting to do something.
Then, shallow your component using shallow(<Button />) and store it in a variable.

Then first, convert output in JSON, using shallowToJson(output) , then expect it to match the snapshot.

Once this test runs, snapshot will be created in test folder and a coverage folder with all details for unit test will be created. Run this index.html and you can see all coverage.

Also, if there are any props available in Component, we can mock props in a variable and pass it to Component when shallow happens. See below code —

Conclusion

This article is to guide developers through basics setup of Jest framework and writing your very first unit test.

--

--

Mohit Khandelwal

Experienced Software Engineer with skilled in React JS, JavaScript, HTML, CSS and Jest. Working as a Senior Technical Consultant at Xebia.