Jest ES6 模块:无法使用 import 语句

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

我正在编写一个 ES6 应用程序。我有

"type": "module"
中的
package.json

devDependencies
是:

  "devDependencies": {
    "@types/jest": "^29.5.12",
    "@types/node": "^20.11.28",
    "coveralls": "^3.1.1",
    "husky": "^9.0.11",
    "jest": "^29.7.0",
    "miragejs": "^0.1.48",
    "npm-check-updates": "^16.14.15",
    "prettier": "^3.2.5",
    "ts-jest": "^29.1.2",
    "ts-node": "^10.9.2",
    "tslint": "^6.1.3",
    "tslint-config-prettier": "^1.18.0",
    "tsx": "^4.7.1",
    "typescript": "^5.4.2"
  }

jest.config.ts
如下:

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  collectCoverageFrom: ["src/**/*.{js,jsx,ts,tsx}"],
  moduleNameMapper: {
    "^public-ip$": "<rootDir>/src/__tests__/__mocks__/publicIp.js", // Mocking the public-ip module
  },
  modulePathIgnorePatterns: [
    "<rootDir>/dist/",
    "<rootDir>/node_modules/",
    "<rootDir>/src/__tests__/__mocks__/",
  ],
  preset: "ts-jest",
  setupFilesAfterEnv: [
    "<rootDir>/jest.setup.js"
  ],
  testEnvironment: "node",
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
};

它可以工作,但是当我在

miragejs
中添加
jest.setup.js
配置时:

import { makeServer } from "./src/__tests__/__mocks__/server";

let server = null;

beforeEach(() => {
  server = makeServer({environment: "test"});
  /**
   * Enable logging of the server
   */
  // server.logging = true;
});

afterEach(() => server.shutdown());

我遇到了臭名昭著的错误:

    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:

    /home/sineverba/sviluppo/personali/docker-cloudflare-ddns/jest.setup.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { makeServer } from "./src/__tests__/__mocks__/server";
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

我尝试过的:

  1. 进口babel:

    npm install --save-dev @babel/core @babel/preset-env @babel/plugin-transform-modules-commonjs

  2. 已将

    babel.config.js
    添加到根项目

    {
      "presets": [
        "@babel/preset-env",
        "@babel/preset-typescript"
      ],
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
    
    
  3. 在启动 Jest 之前在 package.json 中添加了

    node-experimental 
    node --experimental-modules`。

如何消除错误?

  • 应用程序本身可以工作。它运行了。我只有 Jest 有问题。所以,ts-node 已经配置好了。

  • 我使用

    package.json
    ,这是脚本部分:

     "scripts": {
        "start": "npx tsx src/index.ts",
        "build": "tsc",
        "test": "jest --watch",
        "coverage": "jest --coverage",
        "lint": "tslint -p tsconfig.json",
        "prettier": "prettier -c \"src/**/*.ts\"",
        "fixprettier": "prettier --write \"src/**/*.ts\"",
        "prepare": "husky"
      },
    

我编辑

jest.config.ts
如下:

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  collectCoverageFrom: ["src/**/*.{js,jsx,ts,tsx}"],
  extensionsToTreatAsEsm: [".ts"],
  moduleNameMapper: {
    "^public-ip$": "<rootDir>/src/__tests__/__mocks__/publicIp.js", // Mocking the public-ip module
  },
  modulePathIgnorePatterns: [
    "<rootDir>/dist/",
    "<rootDir>/node_modules/",
    "<rootDir>/src/__tests__/__mocks__/",
  ],
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  testEnvironment: "node",
  transform: {
    "^.+\\.tsx?$": [
      "ts-jest",
      ,
      {
        useESM: true,
      },
    ],
  },
};

如果我删除对

miragejs
服务器的引用,Jest 就可以工作(当然,它不再找到导入指令)。

javascript node.js jestjs
1个回答
0
投票

导入 MirageJS 的麻烦似乎与 Jest 设置中如何理解其模块有关。由于 MirageJS 是 Ember CLI 的附加组件,因此其模块系统可能尚未完全准备好与为 ES 模块设置的 Jest 环境无缝协作。

尝试简化打字稿的笑话设置,如下所示:

import type { Config } from '@jest/types';

// Jest configuration for TypeScript with ES Modules
const config: Config.InitialOptions = {
  preset: 'ts-jest/presets/default-esm', // Use the ESM preset for ts-jest
  globals: {
    'ts-jest': {
      useESM: true,
    },
  },
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1', // Redirect .js imports to their .ts counterparts
    '^public-ip$': '<rootDir>/src/__tests__/__mocks__/publicIp.js',
  },
  transform: {}, // Override to prevent jest from transforming
  extensionsToTreatAsEsm: ['.ts'], // Treat .ts files as ES Modules
  testEnvironment: 'node', // Specify the environment in which the tests are run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], // Setup file for Jest
};

export default config;
© www.soinside.com 2019 - 2024. All rights reserved.