Getting into software testing with Jest
Tags: javascript, webdev, react, testing
Published: 2022-03-01 19:46:24

Starting from open-source projects to enterprise software, most softwares have a huge codebase. Don't believe me? Here is a fact! Some of the Google codebases have over 2 billion lines! Understanding and debugging each line manually is something that probably only Superman can do. So when contributing to a project, it is essential to keep in mind that your code doesn't disrupt the existing functionalities.

## What is Testing? 🧪
In software, testing is the process of finding any gap, error, or missing requirements and verifying if it matches our needs.

Suppose you give an input in an electrical DC Machine. With your theoretical knowledge, you will have some expected output right? But in real life the output might be a bit different. So in testing, we generally determine the difference between the expected and the actual values and try to fix it as much as possible.

![Flow Chart describing test workflow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syd9bftjap85383xwrlu.png)

**Software testing is divided majorly into 3 categories:**
- Unit Testing: testing a single function
- Integrating Testing: testing a function that calls a function
- End to End Testing: validating a DOM (i.e. we check if **everything** is in sync)

In this article, let's focus on Unit Testing. Why? Because it is easy to implement and very commonly used.

## But how do we know what to test? 🤓

When it comes to testing, even a simple block of code could paralyse beginners. The most common question is **"How do I know what to test?"**

Suppose we're writing a web application, a good starting point would be testing every page of the app and every user interaction. But, web applications are also made of units of code like functions and modules that need to be tested too.

While writing code, there are mostly two scenarios:

- You inherit **legacy code** which comes **without tests**
- You have to **implement a new functionality** out of thin air

What to do? For both the cases we can think tests to be bits of code that check if a given function produces the expected result or not. Here's how a typical test flow looks like:

- import the function to test
- give an input to the function
- define what to expect as the output
- check if the function produces the expected output

Really, that's it! Testing won't be scary anymore if you think in these terms: 

**input - expected output - assert the result**

## What is Jest? ✨
Jest is a JavaScript testing framework powered by [Meta](https://about.facebook.com/). It focuses more on simplicity and support for large web applications. It is used for testing applications using Babel, TypeScript, Nodejs, React, Angular, Vuejs, and Svelte. Jest is one of the most popular test runners these days and the default choice for **React projects**.

![React x Jest](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smwbu8ui3o1uu39dbmes.jpeg)
 

Jest ships in the NPM package and you can install it in any JavaScript project by running:

```javascript
npm install --save-dev jest 
```
## Let's see a demo 💥

Setting up the project
```javascript
mkdir jestDemo
cd jestDemo
```
Now you are in your directory, so let’s initialise it with NPM.

```javascript
npm init -y
```
The flag -y helps you initialise with all default values. Now, let’s install the jest NPM package.

```javascript
npm install --save-dev jest
```

The project structure is very important, so let’s make it now.

![Project structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ta0er0rbhvrj5coeamh8.png)
 
 
For testing, it is essential to name the testing file with the name of your JavaScript file you want to test and concatenating the word test in between. In this demo we will be testing a script to subtract 2 elements. The script is written in **`subtract.js`** so the corresponding testing file will be **`subtract.test.js`**.

Open up **package.json** and configure a **script** named **test** for running Jest:

```javascript
"scripts": {
   "test": "jest"
},
```

Now we are good to go😁 Let’s start with the scripting of subtract.js and subtract.test.js

In subtract.js:

```javascript
function subtract(a,b){
   return a-b
}
module.exports = subtract
```

In subtract.test.js:

```javascript
const subtract = require('./subtract')
test("Must subtract properly",() =>{
   expect (subtract(1,2)).toBe(-1)
})
```

And that's it! Now let’s test it.

```javascript
npm test
```

After the test, it gives you an output showing the status of the code and comparing it with the actual result and the specified expected value. You will get an output similar to

![Output Status](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8sjel9pghr7bpefplbpa.png)

To get a more detailed and structured visualisation of you tests run:
```javascript
jest --coverage
```

![Coverage CLI Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4em5b7xibg6nw5byq83.png)

![Coverage GUI Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xh4adyy79b78rf9dnppu.png)

Jest coverage command gives a more detailed analysis where the test fails and code can be improved accordingly.

### Outro 💚
Testing is a big and fascinating topic. There are many types of tests and many libraries for testing. In this Jest tutorial, you learnt how to configure Jest for coverage reporting, how to organise and write a simple unit test, and how to test JavaScript code. There’s no better way to test-drive Jest than by diving in and playing with it. 

The purpose of the blog is to create awareness about Jest and similar testing tools. To learn further it is recommended to go through the Jest's official [Documentation](https://jestjs.io/). In case you have some questions regarding the article or want to discuss something under the sun feel free to connect with me on [LinkedIn](https://www.linkedin.com/in/aniket-pal/) 💕

> If you run an organisation and want me to write for you please do connect with me 🙈