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

Node.js React项目Mocha测试中babel-register失效报import语法错误

Fixing "Unexpected token 'import'" in Mocha Tests with babel-register

Hey there, let’s tackle this import syntax error you’re facing with Mocha and babel-register. It’s super frustrating when webpack works fine but tests break—let’s break down what’s going on and fix it step by step.

What’s the Root Issue?

From your error logs, it’s clear that your test_helper.js file isn’t being transpiled by Babel at all—Node is throwing a syntax error on the import statement, which means babel-register isn’t doing its job. This could be due to a few key issues:

  • Misconfigured Babel environment settings (your BABEL_ENV=test might not be applying correctly)
  • Incorrect order of --require flags in your Mocha command
  • A .babelrc that’s not set up to handle test files properly (especially after modifying node_modules:false)
  • Empty targets in your babel-preset-env config, which means Babel doesn’t know which Node version to transpile for

Step-by-Step Fixes

1. Simplify and Reorder Your Mocha Test Command

First, let’s clean up your test script. The babel-hook flag is redundant (you only need babel-register), and we need to ensure babel-register loads before your test helper. Update your package.json scripts:

{
  "scripts": {
    "start": "webpack-dev-server --progress --colors --open --hot",
    "test": "BABEL_ENV=test mocha --require babel-register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  }
}

This ensures Babel registers its loader before any test files are loaded.

2. Fix Your .babelrc for Test Environment

Your current config likely isn’t tailored for the test environment. We need to make sure:

  • For tests, Babel transpiles ES6 modules to CommonJS (so Node can understand them)
  • The targets for babel-preset-env are set to your current Node version
  • We don’t apply unnecessary plugins (like babel-plugin-import for Ant Design) in tests, since we don’t need tree shaking there

Here’s a corrected .babelrc example:

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions"]
      },
      "modules": false
    }],
    "react"
  ],
  "plugins": [
    "transform-class-properties",
    "transform-decorators-legacy",
    "transform-runtime",
    ["import", { "libraryName": "antd", "style": "css" }]
  ],
  "env": {
    "test": {
      "presets": [
        ["env", {
          "targets": {
            "node": "current"
          }
        }],
        "react"
      ],
      "plugins": [
        "transform-class-properties",
        "transform-decorators-legacy"
      ]
    }
  }
}

Key changes for the test environment:

  • targets.node: "current" tells Babel to transpile for your active Node version
  • We omit modules: false (defaults to CommonJS), so Node can handle the transpiled code
  • We remove babel-plugin-import and transform-runtime since they’re not needed for tests

3. Verify the BABEL_ENV is Set Correctly

Add a quick log to your test_helper.js to confirm the test environment is active:

console.log("BABEL_ENV:", process.env.BABEL_ENV); // Should output "test"
import _$ from 'jquery';
// ... rest of your helper code

Run npm run test—if it doesn’t log "test", your environment variable isn’t being set properly. On macOS/Linux, this should work as-is, but if you’re on Windows, install cross-env to set the variable consistently:

npm install cross-env --save-dev

Then update the test script:

"test": "cross-env BABEL_ENV=test mocha --require babel-register --require ./test/test_helper.js --recursive ./test"

4. Double-Check Dependencies

Ensure all your Babel dependencies are compatible (you’re using Babel 6.x, which is fine, but confirm no version conflicts):

  • babel-core@6.x matches babel-register@6.x
  • babel-preset-env@1.7.0 works with Babel 6 (it does, but confirm no version conflicts)

Why This Works

By tailoring your Babel config to the test environment, you’re telling Babel to produce code that Node can execute directly, while keeping your webpack config optimized for browsers. The reordering of --require flags ensures babel-register is active before any test files are loaded, so all import statements get transpiled to require.


内容的提问来源于stack exchange,提问作者user423491

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:41:23