The Talent500 Blog
Jest Tutorial – JavaScript Unit Testing Using Jest Framework 1

Jest Tutorial – JavaScript Unit Testing Using Jest Framework

Facebook created the Jest Javascript Testing Framework. It is primarily intended for React-based apps (which are also produced by Facebook), but it might be used to create automation scenarios for any Javascript-based codebase.

In this Jest testing lesson, we will learn about Jest’s many capabilities, matchers, and how to utilise Jest using an end-to-end example. We will also look at code coverage using Jest.

Installation of JEST

Jest serves as a simple node package that can be installed with any node-based package management.
Example: npm or yarn

Let’s check some sample commands which are used to install Jest package.

yarn add –dev jest
npm install –save-dev jest

To install the Jest module globally, just run the npm command with the ‘-g’ flag. This allows you to utilise Jest commands without having to configure the package file for npm tests.

npm install -g jest

Using Jest In A Node-based Project

To utilise Jest in a node-based project, just run the scripts in the preceding section to install the Jest node package.

To create a node project from start follow the below steps and install Jest into it.

1) With a name as your project nam, create a folder/directory,
For example, myFirstNodeProject

2) Using the terminal or command line, navigate to the project you created in the previous step and run the npm init script using the command below.

npm init

3) When the preceding command is ran, it will prompt for several questions/parameters.

Just keep hitting the enter key (and accept the default values). When finished, a package.json file will be produced in your project. Each node-based project must include this configuration file.

4) Now, use the following command to install the Jest package into the newly formed project.

npm install –save-dev jest

5) We now have a node project with Jest bindings. Let’s set the npm test script to perform Jest tests, which means that when the command ‘npm test’ is invoked, the script should run all Jest framework-based tests.

As shown below, update the package.json file to do that and add a script section.

“scripts”: {

  “test”: “jest”

 }


The final package of the .json file will look as mentioned below.

{

 “name”: “jest-e2e”,

 “version”: “1.0.0”,

 “description”: “”,

 “main”: “index.js”,

 “scripts”: {

   “test”: “jest”

 },

 “author”: “”,

 “license”: “ISC”,

 “dependencies”: {

   “jest”: “^25.1.0”

 }

}

Writing Tests For a Javascript Function

We will construct Jest-based tests for a basic Javascript function code that does addition, subtraction, and multiplication of two integers.

1) Create a js file called calculator in the node project you generated in the previous section. JavaScript with the following contents

const mathOperations = {

   sum: function(a,b) {

       return a + b;

   },

   

   diff: function(a,b) {

       return a – b;

   },

   product: function(a,b) {

       return a * b

   }

}

  module.exports = mathOperations

 

2) Create a test file named calculator.test.js in the same folder for these tests – this is the norm anticipated by the Jest framework to check for all files that include Jest based tests. In order to run the code in the test, we will additionally import the function under test.

This is how the file would appear with only the import / need declaration.

const mathOperations = require(‘./calculator’);

3) Now, in the main file, create tests for the various methods sum, diff, and output.

Jest tests are written in the BDD format, with each test suite containing one main describe block and many test blocks. Please keep in mind that the tests might have nested describe sections as well.

Let’s create a test that adds two numbers and validates the anticipated results. We will input the numbers 1 and 2 and expect the outcome to be 3.

describe(“Calculator tests”, () => {

 test(‘adding 1 + 2 should return 3’, () => {

   expect(mathOperations.sum(1, 2)).toBe(3);

 });

})

Below are the points with reference to the above test:

a) The describe block acts as an outer description for the test suite, acting as a container for all of the tests that will be written for the calculator in this file.

b) After that comes an individual test block, which represents a single test. The string included in quotation marks reflects the test’s name.

c) Look at the code in the expect block – “expect” is just an assertion. The statement invokes the sum method in the function under test with inputs 1 and 2 and anticipates a result of 3.

We may also simplify this to make it easier to grasp.

Please see the example below, where we have separated the function call and assertion into two distinct statements to make it more concise.

describe(“Calculator tests”, () => {

 test(‘adding 1 + 2 should return 3’, () => {

   // arrange and act

   var result = mathOperations.sum(1,2)

 

   // assert

   expect(result).toBe(3);

 });

})

 

d) To run this test, just type “npm test” into the terminal or command line at the project’s directory.

See the below is the output

Jest Tutorial – JavaScript Unit Testing Using Jest Framework 2

4) Let’s try some more tests.

a) Initially, we’ll write a failed test and see what happens. Just alter the result to an inaccurate number in the same test that we wrote in the previous step.

describe(“Calculator tests”, () => {

 test(‘adding 1 + 2 should return 10’, () => {

   // arrange and act

   var result = mathOperations.sum(1,2)

    // assert

   expect(result).toBe(10);

 });

})


In this case, we anticipate a total of 1 and 2 to return 10, which is erroneous.

Jest Tutorial – JavaScript Unit Testing Using Jest Framework 3

When a test fails, you can examine the detailed output, which includes what was actually produced and what was expected, as well as the line in the function under test that caused the issue, and so on.

b) Let’s build some additional tests for the other functions, such as difference and product.

The test file including all of the tests will look like this.

const mathOperations = require(‘./calculator’);

describe(“Calculator tests”, () => {

 test(‘adding 1 + 2 should return 3’, () => {

   // arrange and act

   var result = mathOperations.sum(1,2)

 

   // assert

   expect(result).toBe(3);

 });

 

 test(“subtracting 2 from 10 should return 8”, () => {

   // arrange and act

   var result = mathOperations.diff(10,2)

 

   // assert

   expect(result).toBe(8);

 });

 

 test(“multiplying 2 and 8 should return 16”, () => {

   // arrange and act

   var result = mathOperations.product(2,8)

 

   // assert

   expect(result).toBe(16);

 });

})

After the execution of the above test we get the below output.

Jest Tutorial – JavaScript Unit Testing Using Jest Framework 4

Jest Matchers

Matchers are used in Jest assertions to claim on a condition. Jest makes use of anticipate Api matchers. The expected API documentation can be found here.

Let’s look through some of the commonly used matchers along with Jest tests.

1) Equality

These are the most popular matchers. They are usually utilised for mathematical operations and are used to check equality or inequality.These are the most popular matchers. 

Below are some examples:

We’ve created two matchers using toBe and not toBe which are comparable to Equals and not equals.

test(“equality matchers”, () => {

   expect(2*2).toBe(4);

   expect(4-2).not.toBe(1);

 })


2) Truthiness

Matchers for null, falsy, and truthy, i.e. false and truth values, are shown below. It is critical to understand that everything that is not logically true is false.

For example, number 0, null, empty string, NaN are the examples of falsy w.r.t Javascript.

test(“truthy operators”, () => {

   var name=”Software testing help”

   var n = null

   expect(n).toBeNull()

   expect(name).not.toBeNull

 

   // name has a valid value

   expect(name).toBeTruthy()

 

   //fail – as null is non success

   expect(n).toBeTruthy()

   

   // pass – null treated as false or negative

   expect(n).toBeFalsy()

 

   // 0 – treated as false

   expect(0).toBeFalsy()

 })


3) Number Matchers

These matchers might be used for a variety of mathematical operations.

For example, greaterThan, lessThan, greaterThanOrEqual, etc.

For more details check the below given examples

test(“numeric operators”, () => {

 

   var num1 = 100;

   var num2 = -20;

   var num3 = 0;

 

   // greater than

   expect(num1).toBeGreaterThan(10)

 

   // less than or equal

   expect(num2).toBeLessThanOrEqual(0)

 

   // greater than or equal

   expect(num3).toBeGreaterThanOrEqual(0)

 })

 

4) String Matchers

As an assertion in a Unit test, we frequently require strings to match a regular expression. Jest offers matchers to match strings against a regular expression.

test(“string matchers”,() => {

   var string1 = “software testing help – a great resource for testers”

 

   // test for success match

   expect(string1).toMatch(/test/);

 

   // test for failure match

   expect(string1).not.toMatch(/abc/)

 })

Jest Hooks – Setup And Teardown

Jest framework, like all other xUnit-based unit test frameworks, has hooks for setup and cleanup procedures. These hook methods are called before and after each test in the test suite, or before and after the execution of the testSuite.

There are four hooks available for usage.

  • beforeEach and afterEach hooks: run before and after each test in the test suite.
  • beforeAll and afterAll: performed once per test suite. 

Let’s check the example: These hooks will be added to the same test case of adding two integers.

To demonstrate, we shall set the inputs in beforeEach hook. The test file would look like this with test hooks.

describe(“Calculator tests”, () => {

  var input1 = 0

 var input2 = 0

 

 beforeAll(() => {

   console.log(“beforeAll called”);

 });

 

 afterAll(() => {

   console.log(“afterAll called”);

 });

  beforeEach(() => {

   console.log(“beforeEach called”);

   input1 = 1;

   input2 = 2;

 });

  afterEach(() => {

   console.log(“afterEach called”);

 });

 

 test(‘adding 1 + 2 should return 3’, () => {

   // arrange and act

   var result = mathOperations.sum(input1,input2)

 

   // assert

   expect(result).toBe(3);

 });

})

Conclusion

The Jest testing framework provides an efficient and easy-to-use testing environment for JavaScript unit tests. It is a powerful tool to help developers create robust and bug-free code. Jest tests are fast, reliable, and can be integrated into an automated CI/CD pipeline. By utilising the features of Jest, developers can create reliable and maintainable code that can stand the test of time. In this Jest blog, we went through the basics of the Jest framework, how to install the Jest framework, and saw how it can be used for testing simple JavaScript files. We also looked at the various types of matchers offered by Jest, as well as HTML reporters and code coverage reports.

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment