Skip to content
Learning to write Unit Test

Learning to write Unit Tests

I have recently started writing a number of unit tests and turn out that the more I write the easier it is and there’s always something new, I think there is n no.of ways to write a unit test for a given code, in this post I’ll share some beginner tips to get started, cheers. ✨

Running unit test for one file

Yes we need not run the npm run test command every time and wait for all the tests to finish, we can selectively run the unit test of a single folder or a single file using the below command mentioning the path after the --.

npm run test -- src/component/__tests__/index.test.js

We can also use the --watch mode, however, I found that watch mode can be a bit messy if we are using nodemon or autosave feature.

Maximum unit test coverage with props

To begin with I would recommend this method for simple components, although it works for all kinds of components. First of all, let’s have a look at where the component is being used and then place a debugger or a console log to gather the required props. Now write a simple test to render the component and grab a snapshot of it.

The above steps simulate an ideal case, now we can create 2-3 more variations of the props to test different logic/paths and finally a different set of empty/unexpected props to make sure we got the error handling covered.

Difference between Jest Mock vs Spy

Context: Now while writing unit tests we write tests and expect a component to work as an independent unit but it might have some dependencies of different types like pure functions, side effects, network calls, and third-party libraries so we can either mock them or spy on them.

We use Mock when we want to replace the entire behavior and set a pre-determined return value, on the other hand, we use a spy to actually kind of listen to watch over the dependency or mock it but later restore it again if needed.

Resources on this topic

Blog: Rick Hanlon II [React Core]- Understanding Jest Mocks

YouTube: Justin Searls – Please don’t mock me.