Updated December 12, 2023
What is Jest?
Jest is the most used testing framework for JavaScript projects. Jest has a user-friendly setup for unit testing on React and React-Native-based projects. Jest is simple to perform unit testing and has a time-saving process. You can validate everything that is developed using JavaScript language. Jest has a complete package of a built-in mocking library, test runner, and assertion library. So, Jest is a great testing framework if you want to perform effective unit testing for your JavaScript applications‘ front and back end.
Table of Contents
Different Levels of Testing
Test-driven development (TDD) defines code behavior before implementation, reducing bugs. TDD is an industry-standard that provides insights and reveals unexpected behavior. Tests aid in debugging and enhance code understanding. These are different functional tests:
- Unit Testing: Validates small code units like functions individually.
- Integration Testing: Checks if multiple units work together as expected.
- End-to-end Testing: Emulates actual user behavior for the whole application.
- Acceptance Testing: Ensures the software meets business requirements for functionality compliance.
Why is Jest so popular?
There are various testing frameworks for JavaScript applications, but what makes Jest so widely popular?
- Facebook developed Jest. Due to continuous improvements and upgrades, Jest became a powerful tool. It is used for testing web applications built with various JavaScript libraries like Node.js, Angular.js, Vue.js, TypeScript, and Babel.
- Jest provides high precision and accuracy. It provides a highly useful and familiar API. You can write tests efficiently and get quick results for your code.
- Jest performs faster and safer operations by running tests in parallel. It also ensures that they share a global state. Jest gives priority to previous failed and pending tests first. Then, execute tests based on test file size.
- Programmers can access very well-documented toolkits.
- With Jest, it is unnecessary to depend on third-party tools to access its features. It is remarkably easy to install, set up and run.
- Jest is used for Unit testing, but it can also be used for integration tests.
Features and advantages of Jest
There are various features of Jest are as follows:
1. Jest is easy to install and setup.
The process of installing and setup Jest is very simple. It can be installed using the Yarn library or npm (Node Package Manager). The -g flag is used with the npm command. Jest modules are as simple as Jest commands.
2. Jest has high performance and speed.
Jest executes all test cases efficiently without any delay. Therefore, it saves time, especially when tests depend on CPU performance. The most time-consuming tests run first, so core utilization. Parallel execution of test cases is a highly efficient step.
3. Doing fewer tests
Doing fewer tests can make running all the tests faster. Jest has a pre-commit hooks feature that cuts down on the number of tests run. These are snapshot tests that save time in regression testing.
4. Each test works independently.
Each test runs in its own sandbox. The actions of one test do not affect the performance of another. Even though running tests in parallel is great for speed. Jest framework has fast operation because it isolates test executions. Each test runs in its own environment.
5. Jest supports TypeScript
TypeScript is a superset of JavaScript, and it is used for both server-side and client-side development. Jest supports TypeScript. You can use it from the ts-jest package. It is a typescript preprocessor and provides Jest with source map support.
6. Not relying on external modules.
Jest is a complete and modern testing framework with built-in features, including support for plugins. Unloading external tools like Mocha and Cucumber for specific tasks is unnecessary. If you want to use another library alongside Jest. Then, it is easy to configure without any compatibility issues.
7. Strong support for mocking.
Jest supports mocking, which replaces internal dependencies with objects that can be inspected and controlled. Jest supports various types of mocking, including timer mocking, functional mocking, and mocking individual API calls.
8. Jest provides snapshot testing
Snapshot testing in Jest saves a string representation of a specific component to a file. You can compare these captured values with those from other frameworks. It checks how they align with the expected values. The snapshots represent the state of your components. If there are changes to the UI (user interface), you must update the corresponding snapshot file.
Setup of Jest for Executing any Test or Project
According to Test Driven Development (TDD) guidelines, you write tests before creating business logic units like functions and methods. Testing outlines the code requirements and then verifies that specific part of the code. This process starts with writing a test that will fail. This process starts with writing a test that will fail. Then, we write our business logic code that will pass the test. Finally, we reimplement our tests and code according to lifecycle behavior.
In case you need to test code and existing units without initial testing. Then you can follow this testing approach:
- Select the Code Unit to Test
- Define Input and Expected Output
- Write the Test
- Iterate with Different Inputs
Jest Installation and Configuration
You can install the Jest testing framework using the npm command:
Code:
npm install jest
Save as Dev dependency using the command:
Code:
npm install -save-dev jest
It will save the Jest package manager in node js as a dev dependency.
Selenium WebDriver
Selenium is mainly used for cross-browser testing. You can develop test scripts for specific programming languages suitable for automating the testing process. So, you can apply Selenium across different tech stacks. So, it is a popular choice for testing web applications on various browsers.
You can install Selenium WebDriver using this command:
Code:
npm install selenium-webdriver
After installing it, this will be the package.json file:
Code:
{
"devDependencies": {
"jest": "^29.7.0"
},
"dependencies": {
"selenium-webdriver": "^4.15.0"
}
}
You can view that changed script of jest using this command:
Code:
npm --verbose
The verbose marker in Jest provides a detailed explanation while running tests. So it will be easy to find and understand bugs.
You can run the tests using either of these commands:
Code:
npm test
<!-- or ->
npm run test
<!-- or →
You can use these commands to run specific files to test:
Code:
npx jest -all
<!-- or ->
npx jest <test fineName>
Basics of Jest
To understand the basics of Jest, we will use the following code, a function that has JavaScript code with four functions that perform different operations.
File Name: App.js
Code:
const square = (num) => num * num;
const cube = (num) => num * num * num;
const power = (base, exponent) => Math.pow(base, exponent);
const remainder = (num1, num2) => num1 % num2;
module.exports = {
square,
cube,
power,
remainder
};
Note that you should write tests in files separate from your main code. Use a .test.js extension for your test filenames. The main code and the test file are stored in the same directory.
Now, write sample tests for these functions.
File Name: App.test.js
Code:
const {square, cube, power, remainder} = require('../App');
test('Square of 4 is 16', () => {
expect(square(4)).toBe(16);
});
test('Cube of 3 is 27', () => {
expect(cube(3)).toBe(27);
});
test('2^5 is 32', () => {
expect(power(2, 5)).toBe(32);
});
test('Remainder of 15 divided by 7 is 1', () => {
expect(remainder(15, 7)).toBe(1);
});
Now, you can test these using either of the following commands:
Code:
npx jest
// or
npx jest --all
You will get this output:
We test code using the test function code. The first argument is the function name as a string, and the second is the callback function. A callback function is used to call the unit function. We chain these with “toBe” functions to pass the expected output. Here, it is passed successfully.
Jest Running Example
1. Jest Skipping Test
You do need to execute only some of the tests. You can also run only specific parts of code. To do this, you can skip tests based on your needs. For example, consider following code to skill part of code and test other:
File Name: App.test.js
Code:
const { square, cube, power, remainder } = require('../App');
test('Square of 4 is 16', () => {
expect(square(4)).toBe(16);
});
xtest('Cube of 3 is 27', () => {
expect(cube(3)).toBe(27);
});
test.skip('2^5 is 32', () => {
expect(power(2, 5)).toBe(32);
});
test('Remainder of 15 divided by 7 is 1', () => {
expect(remainder(15, 7)).toBe(1);
});
In this code, we have used `xtest` and `test.skip` to skip tests. The output will be:
2. Jest Parameterized Test
You can execute parameterized tests and pass multiple testing values. You can test all of them using the same function. For example,
File Name: App.test.js
Code:
const { square, cube, power, remainder } = require('../App');
test.each([
[10, 10, 100],
[-1, 2, 1],
[20, 10, 400],
])('Square of %p is %p', (a, b, expected) => {
const result = square(a);
expect(result).toBe(expected, `Square of ${a} is not ${expected}, received: ${result}`);
});
test.each([
[10, 10, 1000],
[30, 50, 27000],
[6, 0, 216],
])('Cube of %p is %p', (a, b, expected) => {
const result = cube(a);
expect(result).toBe(expected, `Cube of ${a} is not ${expected}, received: ${result}`);
});
test.each([
[1, 1, 2],
[0, 0, 1],
[-2, -2, 0.25],
])('2^%p is %p', (a, b, expected) => {
const result = power(2, a);
expect(result).toBe(expected, `2^${a} is not ${expected}, received: ${result}`);
});
test.each([
[2, 2, 0],
[-1, -1, -0],
[20, 5, 0],
])('Remainder of %p divided by %p is %p', (a, b, expected) => {
const result = remainder(a, b);
expect(result).toBe(expected, `Remainder of ${a} divided by ${b} is not ${expected}, received: ${result}`);
});
We are passing arrays of arrays for testing purposes. The output will be,
3. Jest Grouping Test
You can group similar tests in test blocks using describe. For example, consider this described function.
File Name: App.test.js
Code:
const { square, cube, power, remainder } = require('../App');
const { Counter, Palindrome } = require('./strings');
describe('testing string functions', () => {
test.each(["abba", "aba", "ant", "Hannah", "legal", "large"])(
'testing if the string is palindrome or not', (str) => {
expect(Palindrome(str)).toBeTruthy();
},
);
test.each(["a", "bc", "cde", "efg", "lmno"])(
'testing if strings lengths are correct or not', (word) => {
expect(Counter(word)).toBe(word.length);
},
);
});
describe('testing arithmetic operations', () => {
test.each([[10, 10, 100], [-1, 2, 1], [20, 10, 400]])(
'Square of %p is %p', (a, b, expected) => {
expect(square(a)).toBe(expected);
},
);
test.each([[10, 10, 1000], [30, 50, 27000], [6, 0, 216]])(
'Cube of %p is %p', (a, b, expected) => {
expect(cube(a)).toBe(expected);
},
);
test.each([[1, 1, 2], [0, 0, 1], [-2, -2, 0.25]])(
'2^%p is %p', (a, b, expected) => {
expect(power(2, a)).toBe(expected);
},
);
test.each([[2, 2, 0], [-1, -1, -0], [20, 5, 0]])(
'Remainder of %p divided by %p is %p', (a, b, expected) => {
expect(remainder(a, b)).toBe(expected);
},
);
})
You need to group these two JS files.
File Name: strings.js
Code:
const Counter = (string) => string.length
const Palindrome = (string) => string == string.split('').reverse().join('');
module.exports = {Counter , Palindrome};
Now, the output will be,
All tests are not passed because we intentionally added some failing tests to the above tests. You can analyze both failing tests and passing tests.
4. Jest Testing Axios
You need to install it first using the following command:
Code:
npm install axios
Now, a simple get request using Axios. For example,
File Name: Fetcher.js
Code:
const axios = require('axios');
const fetcher = async () => {
try {
const response = await axios.get('https://www.boredapi.com/api/activity?key=7096020');
return response;
} catch (error) {
throw error;
}
};
module.exports = { fetcher };
Now, write a test file for this.
File Name: App.test.js
Code:
const axios = require('axios');
const { fetcher } = require('../Fetcher');
jest.mock('axios');
test('should fetch an activity from API', () => {
const activity = {
"activity": "Practice coding in your favorite language",
"type": "recreational",
"participants": 1,
"price": 0,
"link": "",
"key": "7096020",
"accessibility": 0.1
};
const resp = { data: activity };
axios.get.mockImplementation(() => Promise.resolve(resp));
return fetcher().then(resp => expect(resp.data).toEqual(activity));
});
To resolve an object and simulate the functionality of Axion, we expect a promise. The output of the above test will be,
Limitations of Jest
Jest has some limitations compared to other libraries like Mocha.
- IDE usage can be challenging because of fewer tools and library support.
- There can be delays in the test suite because of using auto-mocking features.
- A snapshot may not be suitable because of the generation of large snapshot files.
Despite these limitations, Jest can still achieve excellent results.
Conclusion
You can reduce bugs and increase the suitability of codes using Test Driven Development. Jest framework is used for Unit Testing. Jest is used for JavaScript projects based on React. It is user-friendly, fast, and has various rich APIs. Jest is easy to install and simple to use. There are multiple features of Jest, like the helper function, zero-configuration, Isolation, application CLI, Snapshots, etc. You can use Jest on legacy applications and on new codes. Jest can test all tests, skip tests, group tests together, and do parameterized tests. You can also use test mock functions, which can fetch functionalities.
FAQs
1. What is Jest, and why is it widely used for JavaScript projects?
Jest is a testing tool for JavaScript applications based on React and React-Native projects. You can perform snapshot and unit tests and ensure the code functions correctly. Using Jest, you can check individual units and parts of codes for bugs in Unit testing. In snapshot testing, you can compare actual output and expected output. Snapshot testing is used to detect unexpected changes. Jest framework provides packages with a built-in mocking library, test runner, and assertion library. This is why it is a great choice for front-end and back-end development unit testing.
2. How does Jest address the challenges in testing, and what are its important features?
Jest framework provides easy installation and setup. Jest has high-speed test execution and can run fewer tests through features like pre-commit hooks. Each test can run independently for fast and efficient testing. Jest supports TypeScript, so there is no need for external modules.
3. Can Jest be integrated with Selenium WebDriver, and how is this achieved?
Yes, Jest can be integrated with Selenium WebDriver for cross-browser testing. Selenium is used to automate web application testing. Selenium is used across different technology stacks. You can install the Selenium WebDriver package using the npm command. Jest and Selenium WebDriver dependencies can be configured in the package.json file.
Recommended Articles
We hope that this EDUCBA information on “Jest Framework” is beneficial to you. You can view EDUCBA’s recommended articles for more information.