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

Svelte v3升级至v4后Jest测试遭遇Unexpected Token错误求助

Svelte v3升级至v4后Jest测试遭遇Unexpected Token错误求助

我按照官方指南把Svelte从v3升级到v4后卡住了,所有测试都失败了,试了好几种方法都没解决。下面是我的项目环境细节和遇到的错误:

项目配置

jest.config.js

// jest.config.js
module.exports = {
  testEnvironment: "jsdom",
  transform: {
    '^.+\\.js$': 'babel-jest',
    '^.+\\.svelte$': 'svelte-jester'
  }
};

package.json

{
  "name": "svelte-app",
  "version": "1.0.0",
  "devDependencies": {
    "@babel/core": "7.23.2",
    "@babel/preset-env": "7.23.2",
    "@ironkinoko/rollup-plugin-styles": "4.0.3",
    "@rollup/plugin-commonjs": "25.0.7",
    "@rollup/plugin-node-resolve": "15.2.3",
    "@rollup/plugin-replace": "5.0.5",
    "@rollup/plugin-terser": "0.4.4",
    "@testing-library/dom": "7.31.2",
    "@testing-library/jest-dom": "5.17.0",
    "@testing-library/svelte": "^4.0.0",
    "babel-jest": "29.7.0",
    "jest": "29.7.0",
    "jest-environment-jsdom": "29.7.0",
    "rollup": "4.2.0",
    "rollup-plugin-livereload": "2.0.5",
    "rollup-plugin-svelte": "7.1.6",
    "svelte": "^4.0.0",
    "svelte-jester": "3.0.0",
    "testing-library-table-queries": "0.2.0"
  },
  "dependencies": {
    "sirv-cli": "2.0.2",
    "svelte-spinner": "2.0.2"
  },
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public",
    "test": "jest",
    "test-watch": "jest --watchAll"
  }
}

报错信息

FAIL  src/EnummerEditor.spec.js
● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration

For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:
/Users/user123/code/zapp/zapp-config-ui/node_modules/@testing-library/svelte/src/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { act, cleanup } from './pure.js'
^^^^^^

SyntaxError: Cannot use import statement outside a module

1 | import '@testing-library/jest-dom/extend-expect';
> 2 | import {render, fireEvent, screen} from '@testing-library/svelte';
| ^
3 | import EnummerEditor from './EnummerEditor.svelte';
4 |
5 | describe('EnummerEditor', () => {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
at Object.require (src/EnummerEditor.spec.js:2:1)

问题原因分析

这个错误说白了就是:@testing-library/svelte 升级到v4后已经完全改成了ES模块(也就是用import/export的那种),但你的Jest还是按旧的CommonJS模式跑,而且Jest默认不会去转换node_modules里的文件,所以它就看不懂@testing-library/svelte里的import语法了。

具体修复步骤

1. 先给Jest加个配置,让它处理@testing-library/svelte

修改jest.config.js,加上transformIgnorePatterns,告诉Jest别跳过对@testing-library/svelte的转换:

// jest.config.js
module.exports = {
  testEnvironment: "jsdom",
  transform: {
    '^.+\\.js$': 'babel-jest',
    '^.+\\.svelte$': 'svelte-jester'
  },
  // 新增这一行,意思是node_modules里除了@testing-library/svelte,其他都忽略转换
  transformIgnorePatterns: ['/node_modules/(?!@testing-library/svelte)']
};

2. 确保Babel配置能转ES模块

如果项目根目录还没有babel.config.js,就新建一个,内容如下:

module.exports = {
  presets: [
    ['@babel/preset-env', {
      targets: {
        node: 'current' // 针对当前Node版本做兼容转换
      }
    }]
  ]
};

这个配置会让Babel把ES模块语法转成Jest能认的CommonJS。

3. 确认svelte-jester的配置没问题

你现在用的svelte-jester v3.0.0是支持Svelte v4的,不过可以给它加个预处理器的配置,确保能正确处理Svelte组件:

// jest.config.js
module.exports = {
  testEnvironment: "jsdom",
  transform: {
    '^.+\\.js$': 'babel-jest',
    // 给svelte-jester加上预处理器配置
    '^.+\\.svelte$': ['svelte-jester', { preprocess: true }]
  },
  transformIgnorePatterns: ['/node_modules/(?!@testing-library/svelte)']
};

如果你的Svelte组件用了预处理器(比如SCSS、TypeScript之类的),这个preprocess: true就很有必要了。

4. 要是上面的方法还不行,试试切换Jest到ESM模式

这是个更彻底的办法,把整个Jest的运行模式改成ESM:

  • 先在package.json里加一行:"type": "module"
  • 然后把jest.config.js改名为jest.config.mjs,并改成ESM语法:
    export default {
      testEnvironment: "jsdom",
      transform: {
        '^.+\\.js$': 'babel-jest',
        '^.+\\.svelte$': 'svelte-jester'
      },
      transformIgnorePatterns: ['/node_modules/(?!@testing-library/svelte)']
    };
    
    不过这个方法需要你所有的测试文件和相关配置都用ESM语法,比如测试文件里的import而不是require,同时可能还要调整Rollup等其他工具的配置,所以优先试试前三个方法。

验证修复

改完之后,重新跑测试命令:

npm run test

应该就能正常跑起来了~

备注:内容来源于stack exchange,提问作者imalik8088

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 08:54:31