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

Next.js+Jest测试报错:Cannot use import statement outside a module

Jest测试中的ES模块语法错误问题

问题详情

执行Jest测试时触发以下错误:

SyntaxError: Cannot use import statement outside a module

错误指向代码行:

30 |   certificateEuropean: '/icons/certificate-european.svg',
      31 |   check: '/icons/check.svg',
    > 32 |   checkGold: '/icons/check-gold.svg',

相关代码

测试代码

import React from 'react';
import { render } from '@testing-library/react';

import { Icon } from '@/components/UI/Icon';

describe('RegistrationForm', () => {
  test('should update and retrieve values correctly', () => {
    render(<Icon type="accreditation" />);
  });
});

Icon组件代码

const iconMap = {
accreditation: '/icons/accreditation.svg',
...
}

export const getIconSrc = (type: IconType): string => iconMap[type];

export const Icon = React.forwardRef<HTMLImageElement, IconProps>(
  ({ type, size, width, alt = '', id, quantity }, ref) => {
    const _size = size ?? 24;
    const _width = width ?? _size;
    const iconSrc = getIconSrc(type);

    return (
      <>
        <img
          data-testid={id}
          className="h-full"
          ref={ref}
          src={iconSrc}
          width={_width}
          height={_size}
          alt={alt}
        />
        {typeof quantity === 'number' && quantity > 0 ? (
          <span>
            {quantity}
          </span>
        ) : null}
      </>
    );
  }
);
Icon.displayName = 'Icon';

当前jest.config.js配置

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

const createJestConfig = nextJest({
  // 提供Next.js应用路径,用于在测试环境加载next.config.js和.env文件
  dir: './',
});

const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  moduleNameMapper: {
    '@/(.*)$': '<rootDir>/src/$1',
    '@@/(.*)$': '<rootDir>/$1',
    '\\.(ttf|otf|eot|svg)$': '<rootDir>/__mocks__/fontMock.js',
  },
  testEnvironment: 'jsdom',
  setupFiles: ['./text-encoder.mock.ts'],
  setupFilesAfterEnv: ['@testing-library/jest-dom'],
};

module.exports = createJestConfig(customJestConfig);

已尝试的方案及新问题

在jest.config.js中添加以下配置:

preset: 'ts-jest',
testEnvironment: // 尝试过所有可能的选项
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
transformIgnorePatterns: ['/node_modules/'],

globals: {
  "ts-jest": {
    isolatedModules: true,
  },
},

同时在package.json中添加"type": "module",,使用node --experimental-vm-modules node_modules/jest/bin/jest.js替代npm test执行测试,结果触发新错误:

Must use import to load ES Module: C:\Users\USERNAME\frontend\node_modules\@sitecore-feaas\clientside\dist\browser\react.esm.js

需求

寻求解决上述ES模块相关测试错误的有效方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:57:38