乐闻世界logo
搜索文章和话题

How to setup jest with node_modules that use es6

1个答案

1

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.

bash
npm 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:

javascript
module.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:

javascript
import { 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:

bash
npm 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.

2024年7月20日 03:34 回复

你的答案