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

Next.js测试中第三方库出现import语句模块外使用错误

解决Jest测试@tanstack/react-query时的"Cannot use import statement outside a module"错误

问题原因

默认情况下Jest会跳过node_modules目录下的代码转译,但@tanstack/react-query发布的是ES模块代码,你的测试环境没对它进行转译,导致出现import语法错误。

解决方案

1. 更新Jest配置,让Jest转译@tanstack/react-query

修改jest.config.js,添加transformIgnorePatterns规则,明确告诉Jest需要转译@tanstack/react-query:

// jest.config.js
const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './'
});

const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  transform: {
    '^.+\.[t|j]sx?$': 'ts-jest'
  },
  // 添加这一行,排除@tanstack/react-query的转译忽略规则
  transformIgnorePatterns: [
    '/node_modules/(?!@tanstack/react-query)'
  ]
};

module.exports = createJestConfig(customJestConfig);

2. 简化Babel配置避免冲突

你的.babelrc中next/babel预设已经包含了React、TypeScript的转译能力,无需重复添加@babel/preset-env和@babel/preset-typescript,简化后配置如下:

{
  "presets": ["next/babel"],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "babel-plugin-parameter-decorator"
  ]
}

3. 确保测试文件的Jest环境正确

确认使用React Query的测试文件顶部已经添加jsdom环境标识:

/** @jest-environment jsdom */

4. 清除Jest缓存并重新测试

执行命令清除Jest缓存,避免旧配置残留影响:

npx jest --clearCache

之后重新运行测试即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:18:55