Jest Testing in JavaScript

Chamindu Jayasith
3 min readJun 2, 2021

Jest is a unit testing in JavaScript, and it is very easy to use. To get started we need to install jest to the project for that in the terminal type npm install --save-dev jest. Jest install as a development dependency because we use testing only in the development process. So, to-do testing I create simple JavaScript code.

In the above JavaScript code basically in the smallnumber() function get two numbers and check whether what number is small and return the smallest number. In the below of the code export smallnumber() function. To test this code using jest we need to create a file. Its name should be filename.test.js or filename.spec.js. you can give whatever you want to filename but after that make sure to give .test.js or .spec.js.That way jest automatically detects files with .test or .spec and run them automatically.

This is the test code for our code. First, need to import out the function which we need to test. After that we type test(), test() function provide by jest this test function allows us to define the single test. This test() function gets two arguments. The first argument is a description which is a description of what we need to test. The second argument is the anonymous function which just the function executes to rerun our test. Inside this anonymous function, we implement our test. expect function is provided by jest. Inside expect function we call our method with passing two numbers. Inside to be we give function which what is expected result for the seallnumber(8,9). To run the test file, add the jest in the script file.

Then type npm test. jest will automatically find test files and execute them. if a test pass in the terminal you will see the test pass with green colour otherwise you will see the test fail because the expected value and actual output doesn’t equal.

--

--