Open In App

jest - npm

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Jest is a JavaScript-based testing framework that is prominently used to ensure the correctness of the Javascript codebase. It is widely based on production-oriented projects where we need testing things to be done so that no code or snippets get pushed by mistake.

Majorly used with React applications but is versatile enough to handle Javascript projects. Created by Facebook, Jest makes the testing simple by providing features like Zero config setup, snapshot testing, and powerful mocking capabilities. Jest can also be put in the CI/CD pipelines in the GitHub Actions or any other things to make the environment more and more automated to compete with the manual checking error. As it is built on the Node.js platform, Jest is available via the npm package manager.

These are the following topics that we are going to discuss:

Features of Jest

Some of the cool and notable features are as follows:

  • Zero Configuration: Jest is easy to set up with no need for entertaining or exclusive configurations.
  • Snapshots: Jest works by capturing our components output and in the future comparing the future outputs test runs with the current one to maintain consistency throughout the development.
  • Mocking: Jest allows us to mock the functions and modules, making it more simple to isolate components during testing.
  • Asynchronous Testing: Jest supports the asynchronous code with async/await, Promises, or callback functions to avoid the NullExceptionError.
  • Parallel Testing: Jest uses the power of Parallel running to optimize performance.
  • Code Coverage: Jest provides powerful code coverage reports generations to help us by ensuring that our tests cover all the important parts of our codebase simultaneously.

Performing Basic Test

Steps to run the test:

  • First install Jest by running:
npm install --save-dev jest
  • Add the following line to your existing package.json to enable running the test with the jest framework:
"scripts": {
"test": "jest"
}
  • Let us write a basic and simple test to check if a function returns the correct output or not.
  • Write this code in your files.
JavaScript
// sum.js
function sum(a, b) {
    return a + b;
}
module.exports = sum;
JavaScript
// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
});
  • Run the tests using the following command:
npm test

Output:

Test-Passed
Test Passed

Asynchronous Testing

Testing the asynchronous code with Jest is straightforward. Here lets explore this with an example of promise:

  • First install the jest as the dev dependencies.
npm install --save-dev jest
  • and then write the following line as the test script in the package.json file
"scripts": {
"test": "jest"
}

Example: This example shows the jest test on the asynchronous function.

JavaScript
// asyncFunction.js
const fetchData = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('data');
        }, 1000);
    });
};

module.exports = fetchData;
JavaScript
// asyncFunction.test.js
const fetchData = require('./asyncFunction');

test('fetches data correctly', async () => {
    const data = await fetchData();
    expect(data).toBe('data');
});


asyncFunction.js

  • The fetchData function returns a promise that resolves with the string 'data' after a 1-second delay usin setTimeOut.

asyncFunction.test.js

  • The test imports the fetchData and uses the Jest framework's test function to check if the fetch is working correctly or not by returning the data. The async keyword allows us to await the promise, ensuring the test waits for the fetchdata results before using except to comapre it with 'data'.
Async-Function-example
Async Function testing example

Conclusion

Jest is a powerful and a easy-to-use tetsing framework used for the javascript based applications and also for the react based applications specifically. It requires zero configurations setup, extensive feature set including mocking, snapshot testing, and also parallel execution, making it an excellent choice for the developers community more productive. Jest helps individual to make sure that their code behaves a s expected while providing fast feedbacks.


Next Article

Similar Reads