You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Jest测试时Babel未将import语句转换为require的问题求助

Jest测试时Babel未将import语句转换为require的问题求助

我在GitHub和Stack Overflow上搜了好多相关问题,试了所有找到的解决方案,但都不管用。看起来所有配置都是正确的,我有一个monorepo,结构是packages/package-apackages/package-b这类。在package-a目录里,我在scripts里配置了Jest测试命令:"test": "jest",我用npm run test -w packages/package-a来运行它。但启动后,我遇到了下面的错误:

Details:

node_modules/components/src/ui/label.js:2
import { jsx as _jsx } from "react/jsx-runtime";

SyntaxError: Cannot use import statement outside a module

    > 1 | import { Label } from '@/ui/label';
        | ^
      2 |
      3 | export function HelloWorld() {
      4 |   return (

对应的组件代码是src/hello-world.tsx

import { Label } from '@/ui/label';

export function HelloWorld() {
  return (
    <h1>
      <Label>Hello World</Label>
    </h1>
  );
}

我的Jest测试文件是__tests__/hello-world.test.tsx

import { render } from '@testing-library/react';
import { HelloWorld } from '../src/hello-world';

describe('Renders the dashboard', () => {
  it('Load Hello World Component', () => {
    const { getByText } = render(<HelloWorld />);
    expect(getByText('Hello World')).toBeInTheDocument();
  });
});

我有两个Jest配置,packages/project-a里的配置会导入根目录的基础配置。基础配置内容如下(省略了和问题无关的部分):

import path from 'path';
const __dirname = new URL('.', import.meta.url).pathname;

export default {
  moduleFileExtensions: ['tsx', 'ts', 'jsx', 'js', 'json', 'node'],
  testMatch: ['<rootDir>/__test(s)?__/**/*.(spec|test).[jt]s?(x)'],
  setupFilesAfterEnv: [path.join(__dirname, 'jest.setup.ts')],
  rootDir: './',
  testEnvironment: 'jsdom',
  transform: {
    '\\.[jt]sx?$': [
      'babel-jest',
      {
        configFile: path.join(__dirname, 'babel.config.cjs'),
      },
    ],
  },
  transformIgnorePatterns: [
    '/node_modules/(?!next-auth|jose|@panva/hkdf|uuid|preact-render-to-string|preact)',
    '^.+\\.module\\.(css|sass|scss)$',
  ],
};

根目录下还有babel.config.cjs文件,用来配置Babel。我试过带插件和不带插件的版本,配置如下:

module.exports = {
  presets: [
    // 'next/babel',
    ['@babel/preset-env', { targets: { node: 'current' } }],
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
  // plugins: [],
  plugins: ['@babel/plugin-transform-modules-commonjs'],
};

注意:Babel配置确实在生效,因为当我把预设/插件改成不存在的名称时,会抛出找不到对应的预设/插件的错误。

为什么Jest没有把import语句转换成可运行的格式呢?


备注:内容来源于stack exchange,提问作者Get Off My Lawn

火山引擎 最新活动