You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在含Puppeteer配置的Jest配置文件中使用ES6模块语法?

Can I use ES6 import syntax in Jest setup/teardown files?

Absolutely! You just need to tweak your Jest and Babel configuration to ensure these setup/teardown files get transpiled—since Jest doesn’t automatically process them with your existing Babel setup by default. Here’s how to make it work step by step:

1. Confirm required dependencies are installed

First, make sure you have the core Babel and Jest transpilation tools in place (they might already be installed if you’re using Babel for your test files):

npm install --save-dev babel-jest @babel/core @babel/preset-env

2. Update your Jest configuration

In your jest.config.js (or the jest field in package.json), configure Jest to use babel-jest for transpiling your files, and ensure your setup/teardown scripts aren’t excluded from processing:

module.exports = {
  // Your existing Puppeteer/test environment settings
  testEnvironment: 'node', // Adjust to 'jsdom' if needed for browser-like tests
  setupFilesAfterEnv: ['./path/to/your/setup-file.js'], // Point to your ES6 setup script
  // Enable Babel transpilation for all .js files
  transform: {
    '^.+\\.js$': 'babel-jest',
  },
  // Keep default exclusion for node_modules (your own files won't be ignored)
  transformIgnorePatterns: ['/node_modules/'],
};

3. Validate your Babel configuration

Your existing .babelrc with the env preset should already handle converting ES6 to CommonJS for Jest, but double-check it’s targeting your Node.js version:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current" // Ensures compatibility with your active Node.js version
      }
    }]
  ]
}

4. Use import in your setup/teardown files

You can now write your Puppeteer setup/teardown logic with ES6 modules seamlessly. For example:

import puppeteer from 'puppeteer';

let browser;

beforeAll(async () => {
  browser = await puppeteer.launch({ headless: 'new' });
});

afterAll(async () => {
  await browser.close();
});

Alternative: Native ES modules (Jest 28+)

If your project uses type: "module" in package.json to enable native ES modules:

  • Rename your Jest config file to jest.config.mjs
  • Ensure you’re using Jest 28 or later
  • Adjust your Babel config to target ES modules if needed

This lets you use import across all files without transpiling to CommonJS, though note some older npm packages might have compatibility issues with native ES modules.


内容的提问来源于stack exchange,提问作者Marcin Goławski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:24:49