Deotyma
Deotyma

Reputation: 948

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

I would like to import an icon from package carbon-icons-svelte to my svelte component. It works very well in browser but I can't test this component. Testes worked good before import of carbon icons. This is my configuration:

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"]
}

I have this information about an error in 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 |
     | ^

I added to jest.config.test.cjs

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

after moduleNameMapper but still it doesn't work. Thanks for your help.

Upvotes: 0

Views: 1302

Answers (1)

Paul Wanjohi
Paul Wanjohi

Reputation: 119

running on node 16, i changed my babel to cjs and it worked for me, this is what it looks like

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

my 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;

Upvotes: 1

Related Questions