The basics about Unit Testing…

So what is exactly is unit testing?! So as you can probably guess, unit testing sounds a lot like its name! It is a type of software testing where individual pieces of code or components of a software are tested. Unit tests isolate some code (function, method, object, module, etc) and verify its correctness. Pretty amazing right?!

Why should we do it?! Unit testing can serve as good documentation and help identify functionality before even writing code, as well as save time and costs — by helping to find bugs early in development and code reuse (just rework the code until the tests run again!)

How do we unit test?! First we are going to use Jest — a JavaScript testing framework that makes our lives very easy! Let’s first install …

Next, make sure to add to your package.json. Now you can run your Jest → npm run test or yarn run test

Below is a simple test called a Sanity check or sanity test is considered basic testing to evaluate whether a claim or result of a calculation can be true. This particular test will assert that we expect the value true to be true.

Now, let’s write a test case in Jest! As you can see from above isInteger.js is a module that takes in a single parameter and returns true is the parameter is an integer, if not it will return false.

We will create two test cases : isInteger() passes for an integer value and isInteger() fails for a non-integer value. We will use the test() function that Jest provides, it takes a test name (which is a string value) and a handler function as the arguments.

Unit tests are based on assertions and assertions are made up of two things: expectations and matchers. The simplest and most common assertion expects the tested value to match a specific value.

Expectation is created with the expect() function which returns an object of matches or matcher methods. The matcher method toBe() checks if the expectation matches a given value.

Now as your code gets more complex there are so many amazing things you can do with Jest — we can distinguish between a null or undefined value as well as grouping test cases together! Explore the docs linked above and happy coding!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
syd

syd

software engineer. red wine addict. obsessed with vintage cars and jewelry.