User photo

How to setup testing in JavaScript

As a programmer, it is essential to know how to test your code. Why? Testing contributes to the overall quality, reliability, and maintainability of software. Here are three reasons why you should test your code:

1.
Identify Bugs Early: Sometimes, as developers (sorry, most of the time), we write code with bugs we can see and some that are playing Jerry on us. Hence, testing the code allows us to bust Jerry's out before they cause damage.
2.
Ensuring reliability: It turns out that trust is also important in programming. Testing your code helps you trust your code and reduces unexpected bugs in your code. And this is crucial when deploying to production.
3.
Maintaining code quality: Often we make changes in our code, and those changes happen to create bugs most of the time. Hence, we need to ensure that our code runs the same through testing instead of “Trust me, bro, it works.”.

In this blog, we are going to explore how to properly setup testing with JavaScript, including how to create and run tests.

Setting up JavaScript environment

Let us create a new JavaScript project using npm and nodejs. Make sure that you have these installed on your PC or laptop. To check if they are installed, run the following commands separately:

# For checking node version node --version # For checking npm version npm --version
Run these commands separately.
For each command, you should get something like this: v18.18.2. Yours will be different than mine or the same depending on the version you installed.
If you get an error, this means you have not installed it correctly. Check the resources on the side bar; you should see a link on how to install nodejs.
Please note:

When you install nodejs, you are also installing npm automatically. So do not worry about installing npm.

Initializing package manager

Now that we have installed what we need, let us get started. Open up a folder where you want to create this project. Open up the folder in your code editor, I am using vscode. Then open the terminal and run the following command:

npm init -y
This will initialize your package manager (npm). If you do not know what a package manager is, check the resources on the side bar.

After initializing, you should see a file called package.jon in your folder. The content inside this file will look like this:

{ "name": "testing-with-javascript", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
Do not worry about the content inside; explaining it will be out of the scope of this blog. Check the resources on the side bar to learn more about it.

After initializing the package manager, create a folder called src, and inside that folder, create a file called index.js. The content of the file can be anything you want, or you can use mine:

function calculateBMI(weight, height) { const bmi = weight / Math.pow(height, 2); return bmi.toFixed(2); } module.exports = calculateBMI;
This function calculates the BMI of a user.
I am using kilograms for the weight and meters for the height.
Make sure you export the function so that it can be used when writing the tests.

Setting up the tests

Now that we have our JavaScript environment setup, let us set up the tests. For the testing, we will be using Jest as our testing library. It is very simple to set up with JavaScript. Let us start by installing the Jest package by using the following commands in your terminal:

npm install -D jest
This will install the jest package from npm.
The -D flags means that we want to install this package as a dev dependency because we only run tests in development not on production.
Please note:

When installing dependencies, if you include the flag -D it means that the dependencies you have installed will only be used in development, else they will be used in both production and development.

Initializing the tests

Inside your project folder, create a folder called test. This is where all your tests will be stored. Then create a new test file, inside this new folder you created, called bmi.test.js or whatever name it has, but it must have .test.js at the end of the name. In the content of the file, you can write your own tests or use mine:

const calculateBMI = require("../src/index"); test("Body Mass Index Calculator test", () => { const userWeight = 70; const userHeight = 1.75; const userBMI = calculateBMI(userWeight, userHeight); expect(userBMI).toBe("22.86"); })
I imported the function I wanted to test.
Then I wrote my tests using the jest syntax for writing tests.
First, define the test which takes in two arguments, which are the test name and the function that will run the test.
I used the jest matchers to test the BMI of a user with a weight of 70kg and a height of 1.75m.

Running the tests

After configuring the JavaScript environment and writing the test, we need to run it. How? Remember that package.json file? Let us modify it to run the test. Only modify the test like this:

"scripts": { "test": "jest" },
I just removed "echo "Error: no test specified" && exit 1" and added jest to the file.
That’s it, your done.

Now let us run the script that we have created. Open up your terminal and run the following command:

npm test
Congratulation ✨, you have created your first test with JavaScript using the jest testing library.
You can now start applying for that Google internship, your ready 😄.

Writing more tests

You can create as many tests as your project scales in the same file, like this:

function calculateBMI(weight, height) { const bmi = weight / Math.pow(height, 2); return bmi.toFixed(2); } function checkEvenOrOdd(number) { if(number % 2 === 0) { return "Even"; } else { return "Odd"; } } module.exports = {checkEvenOrOdd, calculateBMI};
This is the index.js file, where I have written two functions.
You can create another file and store the checkEvenOrOdd there instead, totally up to you.
const {calculateBMI, checkEvenOrOdd} = require("../src/index"); test("Body Mass Index Calculator test", () => { const userWeight = 70; const userHeight = 1.75; const userBMI = calculateBMI(userWeight, userHeight); expect(userBMI).toBe("22.86"); }) test("Check number (even/odd):", () => { const evenNumber = 22; const checkNumber = checkEvenOrOdd(evenNumber); expect(checkNumber).toEqual("Even"); })
This is the bmi.test.js file. You can change the filename to something else since we added new tests; that is up to you.
You can also create a new test file and put the second test there; it is totally up to you.
Please note:

When writing your javascript code, make sure that you always export the code that you want to test, so that you can import it on the tests.

Conclusion

Start writing tests for every project that you make and thank me later, trust me bro. I hope I made it easy for you to understand and follow along. If you have any questions, feel free to post them in the comment section, and by doing that, you will be helping other developers with the same question.