使用 jest 时,React 应用程序中的 import 语句出错

问题描述 投票:0回答:1

我有一个反应应用程序,我正在尝试配置笑话,如果我使用任何导入语句,它会抛出错误

C:\.....ui\src\__tests__\demo.test.jsx:1       
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import "@testing-library/react";
                                                                                      ^^^^^^
    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)

我已经浏览了笑话文档,一些视频仍然不清楚并出现错误

我的package.json

{
  "name": "test-ui",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "start": "vite",
    "test": "jest",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@trimble-oss/modus-icons": "^1.15.0",
    "@trimble-oss/modus-react-components": "^0.36.0-react18",
    "@trimbleinc/modus-react-bootstrap": "^1.2.4",
    "axios": "^1.7.7",
    "date-fns": "^4.1.0",
    "express": "^4.21.1",
    "gulp": "^5.0.0",
    "jwt-decode": "^3.1.2",
    "react": "^18.3.1",
    "react-bootstrap": "^2.10.4",
    "react-dom": "^18.3.1",
    "react-router-dom": "^6.26.1"
  },
  "devDependencies": {
    "@babel/core": "^7.26.0",
    "@babel/preset-env": "^7.26.0",
    "@babel/preset-react": "^7.26.3",
    "@testing-library/jest-dom": "^6.4.6",
    "@testing-library/react": "^16.0.0",
    "@testing-library/user-event": "^14.5.2",
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "@vitejs/plugin-react": "^4.3.1",
    "babel-jest": "^29.7.0",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.2",
    "eslint-plugin-react-hooks": "^4.6.2",
    "eslint-plugin-react-refresh": "^0.4.7",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "vite": "^5.3.1"
  }
}

babel.cofig.js

module.exports = {
    presets: ["@babel/preset-env", "@babel/preset-react"],
};

jest.config.cjs

/*
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */

module.exports = {
  // Indicates whether the coverage information should be collected while executing the test
  collectCoverage: true,
  // The directory where Jest should output its coverage files
  coverageDirectory: "coverage",
  // A list of reporter names that Jest uses when writing coverage reports
  coverageReporters: [
    "json",
    "text",
    "lcov",
    "clover"
  ],
  // An array of file extensions your modules use
  moduleFileExtensions: ["js", "jsx", "json", "node"],
  // The test environment that will be used for testing
  testEnvironment: "jsdom",
  // The glob patterns Jest uses to detect test files
  testMatch: [
    "**/__tests__/**/*.[jt]s?(x)",
    "**/?(*.)+(spec|test).[tj]s?(x)"
  ],
  // A map from regular expressions to paths to transformers
  transform: {
    '^.+\\.(ts|tsx|jsx|js)$': 'babel-jest',
    '^.+\\.(css)$': '<rootDir>/fileTransform.cjs',
  },
  // Indicates whether each individual test should be reported during the run
  verbose: true,
  extensionsToTreatAsEsm: [".jsx"],
};

vite.config.js

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': '/src',
    },
  },
});

我的测试用例是

import "@testing-library/react";
import { render, screen } from "@testing-library/react";
import Button from "./Button";

test("renders the button with the correct label", () => {
  //   render(<Button label="Click Me" />);
  expect(1).toBe(1);
});

在保留 import 语句的同时配置 jest 的正确方法是什么?

javascript reactjs jestjs vite
1个回答
0
投票

我已复制您的配置并尝试在我的计算机上重现该错误。 使用您的配置进行最简单的设置可以正常工作,我可以开始测试而不会出现任何错误。 只有当我像这样更改 jest.config 时,我才会遇到您的错误:

transform: {
    '^.+\\.(ts|tsx|js)$': 'babel-jest', //deleted here jsx to exlude such files from babel transpilation
  },

  transfrom: {}  //exlude all files from transpilation

似乎在您的本地设置中 babel-jest 无法正确转换 jsx 文件(不知道为什么)。我会尝试删除 node_modules、package-lock、清理 npm 缓存并从头开始重新安装所有 deps。

© www.soinside.com 2019 - 2024. All rights reserved.