Step 1: Install Jest and Related Dependencies
First, install Jest in your project. If your project uses Babel to support ES6 or higher JavaScript, you also need to install babel-jest and @babel/core.
bashnpm install --save-dev jest babel-jest @babel/core
Step 2: Configure Babel
To enable Jest to understand ES6 code, configure Babel. Create a .babelrc file or add Babel configuration to package.json. Here is a basic Babel configuration example; we use @babel/preset-env to transpile ES6 code.
json{ "presets": ["@babel/preset-env"] }
Step 3: Configure Jest
Next, configure Jest to use Babel. Create a jest.config.js file in the project root and add the following configuration:
javascriptmodule.exports = { transform: { '^.+\.(js|jsx)$': 'babel-jest' }, testEnvironment: 'node' // Run tests in the Node.js environment };
The transform field tells Jest how to handle .js or .jsx files, using babel-jest for transpilation.
Step 4: Write Tests
Now that everything is configured, you can start writing test code. Here is a simple test example for a function sum.js:
javascript// sum.js export const sum = (a, b) => a + b;
The corresponding test file sum.test.js:
javascriptimport { sum } from './sum'; test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
Step 5: Run Tests
Finally, run the tests using the following command:
bashnpm test
Or add a test script to package.json:
json"scripts": { "test": "jest" }
This is the basic process for configuring Jest in a project using ES6 syntax.