Skip to main content

Jest for JavaScript

Jest is a fast, flexible, and popular testing framework for JavaScript projects. This guide will help you set up Jest in an existing JavaScript project to start writing and running tests effortlessly.


Prerequisites

Ensure the following dependencies are installed in your project:

  1. Jest: Install Jest in your project and ts-jest, a TypeScript preprocessor for Jest:
    npm install jest --save-dev

  1. Babel (Optional): If your project uses modern JavaScript syntax (e.g., ES6+), install Babel and the Jest Babel preset:
npm install @babel/preset-env babel-jest --save-dev

Then, create or update your .babelrc file with the following configuration:

{
"presets": ["@babel/preset-env"]
}

Configuration Steps

  1. Add Jest Configuration

Create a jest.config.js file in the root of your project with the following content:

module.exports = {
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).js?(x)'], // Matches test files
collectCoverageFrom: [
'src/**/*.{js,jsx}', // Include source files
'!src/**/*.d.ts', // Exclude declaration files
],
coveragePathIgnorePatterns: [
'/node_modules/' // Exclude node modules
],
};

  1. Add Test Scripts

Update your package.json to include test scripts:

"scripts": {
"test": "jest",
"test:watch": "jest --watch",
}

  1. Write a Test

Create a test file in your project, for example, src/sample.test.js:

function sum(a: number, b: number): number {
return a + b;
}

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

  1. Run Tests

Run your tests using the following script:

npm test

With this setup, your JacaScript project is ready to leverage Jest for robust and efficient unit testing. Happy testing!