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

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.

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;

Related

Unable to resolve module when using babel module resolver + eslint + index files in react application

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;
There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

Jest Test Support for the experimental syntax 'jsx' isn't currently enabled

I am writing first tests for my app and just install Jest.
My test is pretty simple, so I don't think the error I am getting is coming from there.
import React from 'react';
import renderer from 'react-test-renderer';
import FancyInput from './FancyInput';
describe('FancyInput', () => {
it('should render correctly', () => {
expect(
renderer.create(
<FancyInput />
)
).toMatchSnapshot();
});
});
Error when run the test is Support for the experimental syntax 'jsx' isn't currently enabled
also
`Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.`
My webpack file has the following thing:
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
],
plugins: [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-optional-chaining"],
["#babel/plugin-syntax-jsx"],
]
}
}
},
also my package.json has all the plugins I believe are necessary
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/plugin-proposal-decorators": "^7.4.4",
"#babel/plugin-proposal-optional-chaining": "^7.11.0",
"#babel/plugin-syntax-jsx": "^7.10.4",
"#babel/preset-react": "^7.0.0",
what am I missing here ?

How to integrate Material UI into Svelte project

I want to integrate Material UI into my Svelte project.
I tried to follow the official documentation from here, but I don't know why I'm getting a strange error while trying to run my project:
loaded rollup.config.js with warnings
(!) Unused external imports
default imported from external module 'rollup-plugin-postcss' but never used
rollup v1.27.13
bundles src/main.js → public/build/bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src/views/App.css (1:0)
1: .footer.svelte-1xl6ht0{position:fixed;left:0;bottom:0;width:100%;background-color:#569e3e;color:white;text-align:center;height:15px}.footer.us.svelte-1xl6ht0,.footer.europe.svelte-1xl6ht0,.footer.central.svelte-1xl6ht0,.footer.south.svelte-1xl6ht0,.footer.apac.svelte-1xl6ht0,.footer.baldr.svelte-1xl6ht0{background-color:#ca4a4a}.footer
....
The problem seems to be related to CSS.
In my src directory I have a directory called theme which contains a file called _smui-theme.scss and this is the content of the file:
#import "#material/theme/color-palette";
// Svelte Colors!
$mdc-theme-primary: #ff3e00;
$mdc-theme-secondary: #676778;
// Other Svelte color: #40b3ff
$mdc-theme-background: #fff;
$mdc-theme-surface: #fff;
$mdc-theme-error: $material-color-red-900;
And here is my rollup.config.json file:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
In order to solve this issue a postcss plugin is needed for rollup.
I have also added a svelte preprocessor (I think this is optional, but I wanted to be sure).
Make sure you install this packages with npm or yarn:
rollup-plugin-postcss and svelte-preprocess
Then the plugins should be added in rollup.config.js like this:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss'; <<<------------- Add this
import autoPreprocess from 'svelte-preprocess'; <<<------------- Add this
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
preprocess: autoPreprocess() <<<------------- Add this
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
postcss({ <<<------------- Add this
extract: true,
minimize: true,
use: [
['sass', {
includePaths: [
'./src/theme',
'./node_modules'
]
}]
]
}),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Now everything should be working right with the css and Material UI can be used.

Protractor W3C capability

I am using Protractor with Selenoid. I need to use the dockerized Windows images so that I can test Internet Explorer and Edge from Linux boxes.
I was able to make it work from curl by running:
curl -X POST http://127.0.0.1:4444/wd/hub/session -d '{"capabilities":{"browserName":"MicrosoftEdge","count":1,"alwaysMatch":{"browserName":"MicrosoftEdge","selenoid:options":{"enableVNC":true,"enableVideo":false,"enableLog":true,"logName":"edge-18.0.log"}}}}'
My protractor config looks like:
multiCapabilities: [
{
browserName: "MicrosoftEdge",
"alwaysMatch": {
browserName: "MicrosoftEdge",
"selenoid:options": {
enableVNC: true,
enableVideo: false,
enableLog: true,
logName: "edge-18.0.log"
}
}
}
]
But protractor send it over the selenoid server like this:
{
"desiredCapabilities": {
"browserName": "MicrosoftEdge",
"count": 1,
"alwaysMatch": {
"browserName": "MicrosoftEdge",
"selenoid:options": {
"enableVNC": true,
"enableVideo": false,
"enableLog": true,
"logName": "edge-18.0.log"
}
}
}
}
The issue is that desiredCapabilities should just be 'capabilities`. I have been looking everywhere trying to find out where is that created so that I can created some sort of flag to be able to switch it.
Any ideas?
Using Protractor 6.0 solve my issue, but broke all my tests.
I was able to keep using 5.4.1 by patching the selenium-webdriver package. Looking at the way Protractor 6 did it, I did it to Protractor 5.4.1:
I edited the file located at node_modules/selenium-webdriver/lib/webdriver.js and added the following:
// Capability names that are defined in the W3C spec.
const W3C_CAPABILITY_NAMES = new Set([
'acceptInsecureCerts',
'browserName',
'browserVersion',
'platformName',
'pageLoadStrategy',
'proxy',
'setWindowRect',
'timeouts',
'unhandledPromptBehavior',
]);
Then in the same file I modify the static createSession(executor, capabilities, opt_flow, opt_onQuit) method to add the following:
let W3CCaps = new Capabilities(capabilities);
for (let k of W3CCaps.keys()) {
// Any key containing a colon is a vendor-prefixed capability.
if (!(W3C_CAPABILITY_NAMES.has(k) || k.indexOf(':') >= 0)) {
W3CCaps.delete(k);
}
}
cmd.setParameter('capabilities', W3CCaps);
After all those changes the request getting to Selenoid is like this:
{
"desiredCapabilities": {
"browserName": "MicrosoftEdge",
"version": "18.0",
"enableVNC": true,
"enableVideo": false,
"count": 1
},
"capabilities": {
"browserName": "MicrosoftEdge"
}
}
And my Protractor 5 config looks like this:
multiCapabilities: [{
browserName: 'MicrosoftEdge',
version: '18.0',
enableVNC: true,
enableVideo: false
}]
Note:
So that I don't have to worry about refresh installs or updates I use the package patch-package (https://github.com/ds300/patch-package) to create a patch that is applied when any of those events happen. Here is a great video explaining how to use that package https://www.youtube.com/watch?v=zBPcVGr6XPk

Webpack / typescript require works but import doesn't

I'm trying to import a node_module into a TypeScript file. I'm using an adaptation of angular2-webpack-starter for my project structure.
import ace from 'brace';
In one of my files gives me
Cannot find module 'brace'.
But
var ace = require('brace');
Works fine. According to this issue I shouldn't be having any problems.
My webpack config file is copied from angular2-webpack-starter.
My tsconfig.json is as follows
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
},
"files": [
"src/bootstrap.ts",
"src/vendor.ts",
"src/polyfills.ts"
],
"filesGlob": [
"./src/**/*.ts",
"!./node_modules/**/*.ts"
],
"compileOnSave": false,
"buildOnSave": false
}
Why would one work but not the other?
The answer is related to this issue. If a module doesn't have type data available (via a .d.ts file), the ES6 module syntax
import name from "module-name";
import * as name from "module-name";
import { member } from "module-name";
//etc
will not work and one must use the CommonJS alternative,
var name = require("module-name");