【问题标题】:Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token当从 node_modules 内部导入 carbon-icons-svelte 时无法在 svelte 组件中使用 Jest 测试错误:Jest 遇到了意外的令牌
【发布时间】:2022-01-19 16:51:18
【问题描述】:

我想从 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"]
}

我有以下关于开玩笑错误的信息:

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 之后,但它仍然不起作用。 感谢您的帮助。

【问题讨论】:

    标签: import jestjs svelte sveltekit svelte-jester


    【解决方案1】:

    在节点 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;
    

    【讨论】:

    • 我试过 vitest 来运行我的测试,他们很高兴,演示 -> gitlab.com/paulwvnjohi/hello-vitest。如果你有我推荐的带宽,搬过来不会超过 2 小时
    • 您的 vitest 演示实际上不包含碳图标。如果我使用该演示导入碳图标,则会收到错误 Directory import './node_modules/carbon-icons-svelte/lib/Accessibility16' is not supported resolving ES modules imported from ./node_modules/carbon-icons-svelte/lib/index.js
    • 我在 node_modules 中有它。
    猜你喜欢
    • 2020-10-01
    • 2019-12-09
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多