Photo by Nguyen Dang Hoang Nhu on Unsplash
JavaScript test using Jest
Simple unit test in JavaScript using Jest
Table of contents
Hi!
This time I will try to create simple test using Jest.
Test are important to check your code before launching the product. You can be sure then that your code works as expected.
While learning I did not come across test, because I guess in simple web page projects there is not much to test. You can just visually see if everything is working. But with more complex apps it can be very useful.
Preparation
First thing that we will need to use our Jest library is package.json. We can generate it typing command below.
npm init -y
Next we will need to install Jest with command
npm install --save-dev jest
Now in our package.json file we can change
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
to
"scripts": {
"test": "jest"
},
This will allow us to type npm test, and call our tests.
Function for testing
We need to create simple function that we will be able to test. For this we will write sum function. It is important to export the sum function, so we can use it in out test.
function sum(a,b){
return a+b
}
module.exports = sum
Test function
Now we need to create file, name convention is to use same name as our js file that we are testing and add test to it. So in my case I created sum.test.js
As we exported our sum, here we can import it.
To write our test we call test() function provided by Jest library.
First parameter is our test name. Here we should describe what is the purpose of the test. So in our case test should check if adding two numbers works.
Second parameter will be arrow function that will execute our test.
Again using functions provided by Jest we can use expect() and toBe() to complete our test.
const sum = require('./sum')
test('adds two numbers', () => {
expect(sum(1,2)).toBe(3)
})
Now if we run npm test, we should receive below result
If you find any mistakes or you have ideas how to refactor my solutions to be simplier/ better please let me know :)