Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token

Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token

我想从 carbon-icons-svelte 包中导入一个图标到我的 svelte 组件中。它在浏览器中运行良好,但我无法测试该组件。在导入碳图标之前,睾丸工作良好。 这是我的配置:

svelte.config.test.cjs

const preprocess = require('svelte-preprocess');
require('dotenv').config()

module.exports = {
    preprocess: preprocess({
        replace: [[/import.meta.env.([A-Z_]+)/, (importMeta) =>
        { return JSON.stringify(eval(importMeta.replace('import.meta', 'process')))} ]]
    })
};

jest.config.cjs

const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');

module.exports = {
    transform: {
        '^.+\.svelte$': [
            'svelte-jester',
            {
                preprocess: './svelte.config.test.cjs'
            }
        ],
        "^.+\.(js)$": "babel-jest",
        '^.+\.(ts)$': [require.resolve('jest-chain-transform'),
            { transformers: ['../../../build-utils/importMetaTransformer.cjs', 'ts-jest'] }
        ]
    },
    testMatch: ["**/spec/**/*.js"],
    moduleFileExtensions: ['js', 'ts', 'svelte'],
    setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};

tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node",
    "module": "es2020",
    "lib": ["es2020", "DOM"],
    "target": "es2019",
    "importsNotUsedAsValues": "error",
    "allowSyntheticDefaultImports": true,
    "isolatedModules": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "allowJs": true,
    "checkJs": true,
    "paths": {
      "$/*": ["src/*"]
    }
  },
  "include": [
    "src/**/*.d.ts",
    "src/**/*.js",
    "src/**/*.ts",
    "src/**/*.svelte",
    "src/**/*.svelte-kit",
    "./jest-setup.ts"
  ],
  "exclude": ["node_modules"]
}

我有关于 jest 错误的信息:

Test suite failed to run                                                                                                                          
                                                                                                                                                  
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.
 • 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/dev/src/iroco-app-client/node_modules/carbon-icons-svelte/lib/Information32/Information32.svelte:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<script>
                                                                                  ^

SyntaxError: Unexpected token '<' 

   9 |   import { createPopper } from '@popperjs/core';
  10 |   import Information32 from 'carbon-icons-svelte/lib/Information32/Information32.svelte';
> 11 |
     | ^

我添加到jest.config.test.cjs

transformIgnorePatterns: ["<rootDir>/node_modules/(?!(carbon-icons-svelte))"]

在 moduleNameMapper 之后,但它仍然不起作用。 感谢您的帮助。

运行 在节点 16 上,我将 babel 更改为 cjs,它对我有用,这就是它的样子

module.export = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript']
};

我的jest.config.js

const config = {
  testEnvironment: 'jsdom',
  transform: {
    '^.+\.js$': 'babel-jest',
    '^.+\.ts$': 'ts-jest',
    '^.+\.svelte$': ['svelte-jester', { preprocess: true }]
  },
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!(carbon-icons-svelte))',
    '<rootDir>/node_modules/(?!(carbon-components-svelte))'
  ],
  moduleFileExtensions: ['js', 'ts', 'svelte']
};

export default config;