nx jest cannot find module `./.config/babel.config` - jestjs

I have an app inside my nx project, which uses array-move.
When writing a test for this app, jest crashes with:
Details:
.../node_modules/array-move/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export function arrayMoveMutable(array, fromIndex, toIndex) {
^^^^^^
SyntaxError: Unexpected token 'export'
Updating the jest configuration
Therefore, I've modified the jest config like this:
+ // Add modules to transform
+ const esModules = ['array-move'].join('|')
module.exports = {
displayName: 'project',
preset: '../../jest.preset.js',
+ transformIgnorePatterns: [`node_modules/(?!${esModules})/`],
transform: {
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '#nrwl/react/plugins/jest',
'^.+\\.[tj]sx?$': 'babel-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/apps/project,
collectCoverageFrom: [
'**/*.{ts,js,jsx,tsx,mjs}',
'!.storybook/**/*',
'!**/*.stories.tsx',
'!src/environments/**/*',
],
}
Follow up error (where I'm stuck at)
However, I ended up with the following error:
Cannot find module './.config/babel.config'
Require stack:
- .../node_modules/#babel/core/lib/config/files/configuration.js
- .../node_modules/#babel/core/lib/config/files/index.js
- .../node_modules/#babel/core/lib/index.js
- .../node_modules/jest-snapshot/build/InlineSnapshots.js
- .../node_modules/jest-snapshot/build/State.js
- .../node_modules/jest-snapshot/build/index.js
- .../node_modules/jest-runtime/build/index.js
- .../node_modules/#jest/core/build/cli/index.js
- .../node_modules/#jest/core/build/jest.js
- .../node_modules/jest/build/jest.js
- .../node_modules/#nrwl/jest/src/executors/jest/jest.impl.js
- .../node_modules/nx/src/config/workspaces.js
- .../node_modules/nx/src/command-line/run.js
- .../node_modules/nx/bin/run-executor.js
Require stack:
.../node_modules/#babel/core/lib/config/files/configuration.js
.../node_modules/#babel/core/lib/config/files/index.js
.../node_modules/#babel/core/lib/index.js
.../node_modules/jest-snapshot/build/InlineSnapshots.js
.../node_modules/jest-snapshot/build/State.js
.../node_modules/jest-snapshot/build/index.js
.../node_modules/jest-runtime/build/index.js
.../node_modules/#jest/core/build/cli/index.js
.../node_modules/#jest/core/build/jest.js
.../node_modules/jest/build/jest.js
.../node_modules/#nrwl/jest/src/executors/jest/jest.impl.js
.../node_modules/nx/src/config/workspaces.js
.../node_modules/nx/src/command-line/run.js
.../node_modules/nx/bin/run-executor.js
at loadConfig (../../node_modules/#babel/core/lib/config/files/configuration.js:172:5)
at loadConfig.next (<anonymous>)
at mergeExtendsChain (../../node_modules/#babel/core/lib/config/config-chain.js:387:45)
at mergeExtendsChain.next (<anonymous>)
at ../../node_modules/#babel/core/lib/config/config-chain.js:373:20
at loadFileChain (../../node_modules/#babel/core/lib/config/config-chain.js:232:24)
at loadFileChain.next (<anonymous>)
I have a .babelrc in the root of the nx app, and there is a babel.config.json in the project root.

Related

nuxt3 + #nuxt/content ... ERROR Failed to parse source for import analysis because the content contains invalid JS syntax

I would like to use nuxt/content for some content from a database. When starting the development environment with npm run dev I get the following message
ERROR Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
and
[Vue warn]: Failed to resolve component: nuxt-content
my config
//nuxt.config.ts
export default defineNuxtConfig({
modules: [
'#nuxtjs/tailwindcss',
'#pinia/nuxt',
'#nuxt/content',
],
imports: {
dirs: ['stores'],
},
buildModules: [
'#nuxt/postcss8',
'#pinia/nuxt',
],
build: {
postcss: {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
},
},
css: [
'#/assets/style/main.scss',
],
})
When i remove the module #nuxt/content the error message also disappears.
By the way, I use vite in this project.

Jest aliases not working with sveltekit/vite

Here is the error:
$ z front
➜ Catalyze-frontend git:(more-tests) ✗
$ npm run test:jest
> catalyze-frontend#0.0.1 test:jest
> jest --rootDir ./src
Error: Jest: Failed to parse the TypeScript config file /home/ettinger/src/oblivion/Catalyze-frontend/jest.config.ts
Error: Must use import to load ES Module: /home/ettinger/src/oblivion/Catalyze-frontend/jest.config.ts
require() of ES modules is not supported.
require() of /home/ettinger/src/oblivion/Catalyze-frontend/jest.config.ts from /home/ettinger/src/oblivion/Catalyze-frontend/node_modules/#jest/core/node_modules/jest-config/build/readConfigFileAndSetRootDir.js is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
Instead change the requiring code to use import(), or remove "type": "module" from /home/ettinger/src/oblivion/Catalyze-frontend/package.json.
at readConfigFileAndSetRootDir (/home/ettinger/src/oblivion/Catalyze-frontend/node_modules/#jest/core/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:136:13)
at async readConfig (/home/ettinger/src/oblivion/Catalyze-frontend/node_modules/#jest/core/node_modules/jest-config/build/index.js:233:18)
at async readConfigs (/home/ettinger/src/oblivion/Catalyze-frontend/node_modules/#jest/core/node_modules/jest-config/build/index.js:420:26)
at async runCLI (/home/ettinger/src/oblivion/Catalyze-frontend/node_modules/#jest/core/build/cli/index.js:132:59)
at async Object.run (/home/ettinger/src/oblivion/Catalyze-frontend/node_modules/jest-cli/build/cli/index.js:155:37)
➜ Catalyze-frontend git:(more-tests) ✗
Here is my jest.config.ts:
export default {
verbose: true,
testEnvironment: 'jsdom',
transform: {
'^.+\\.svelte$': [
'svelte-jester',
{
preprocess: true
}
],
'^.+\\.js$': 'babel-jest',
'^.+\\.ts$': 'ts-jest'
},
moduleFileExtensions: ['js', 'ts', 'svelte'],
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
moduleNameMapper: {
'^$components(.*)$': '<root-dir>/src/components$1'
}
};
I believe package.json has type: "module" which is causing the issue however sveltekit/vite require this. So I don't know how to fix.

Azure Pipeline - Caching NPM - Jest Unexpected token ]

I have a monorepo with Lerna and yarn workspaces. I use Azure Devops to build and publish the application.
Commands
"emis-app:test": "yarn --cwd apps/my-app test", is located on the root package.json
What works
When there is a cache miss or when I don't cache NPM modules,
yarn my-app:test which then trigger yarn --cwd apps/my-app test is successful
What does not work
When the cache is used yarn emis-app:test which then triggers yarn --cwd apps/my-app test does not work and tests are failing.
Here is the output of the cache hit
Resolving key:
- **/yarn.lock, !**/node_modules/**/yarn.lock, !*... [file pattern; matches: 4]
- s/apps/my-app/yarn.lock --> 0E8B2ACAB9CF0A6F80305D0BD6C99FDFA703EE248C33DB254DF57F46CC67B6AF
- s/apps/my-app-1/yarn.lock --> 95AB055F93FBE7A5E118B9C1391F81E1E9885D5ED5F0B6EAAB46985D0619C81D
- s/libs/my-lib/yarn.lock --> C8B48CB9F78F4AAE95941EE10588B139FEE51E2CEDA3313E7FE2B78A32C680B0
- s/yarn.lock --> 31D5354CDC72614EEE3B29335A5F6456576FAEF27417B811967E7DDA9BD91E48
Workspaces
"workspaces": {
"packages": [
"apps/*",
"libs/*"
]
}
Each app is a vue application. Each app contains its own package.json, babel.config, jest.config etc.
jest.config.base extended in each app.
module.exports = {
preset: '#vue/cli-plugin-unit-jest/presets/typescript-and-babel',
transform: {
'vee-validate/dist/rules': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'^.+\\.(ts|tsx)$': 'ts-jest',
},
testMatch: [
'**/*.(spec|test).(js|jsx|ts|tsx)',
],
testEnvironmentOptions: {
// Allow test environment to fire onload event
// See https://github.com/jsdom/jsdom/issues/1816#issuecomment-355188615
resources: 'usable',
},
reporters: [
'default',
[
'jest-trx-results-processor',
{
outputFile: './coverage/test-results.trx',
defaultUserName: 'user name to use if automatic detection fails',
},
],
],
moduleFileExtensions: [
'js',
'ts',
'json',
'vue',
],
testURL: 'http://localhost/',
snapshotSerializers: [
'jest-serializer-vue',
],
runner: 'groups',
};
jest.config (my-app)
const baseConfig = require('../../jest.config.base');
const packageJson = require('./package.json');
module.exports = {
...baseConfig,
transformIgnorePatterns: [],
roots: [
'<rootDir>/src',
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'^#libs/registration-lib/(.*)$': '<rootDir>/../../libs/registration-lib/src/$1',
},
name: packageJson.name,
displayName: packageJson.name,
};
Questions
Am I using the cache correctly?
Is it possible to use the caching when working with workspaces
Errors
FAIL #apps/my-app src/ui/views/pages/registration/individual/Individual.vue.spec.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
SyntaxError: Unexpected token ] in JSON at position 467
at JSON.parse (<anonymous>)
at parse (../../node_modules/tsconfig/src/tsconfig.ts:195:15)
at readFileSync (../../node_modules/tsconfig/src/tsconfig.ts:181:10)
at Object.loadSync (../../node_modules/tsconfig/src/tsconfig.ts:151:18)
at find (../../node_modules/vue-jest/lib/load-typescript-config.js:33:39)
at loadTypescriptConfig (../../node_modules/vue-jest/lib/load-typescript-config.js:73:26)
at compileTypescript (../../node_modules/vue-jest/lib/compilers/typescript-compiler.js:9:20)
at processScript (../../node_modules/vue-jest/lib/process.js:23:12)
at Object.module.exports [as process] (../../node_modules/vue-jest/lib/process.js:42:18)
at ScriptTransformer.transformSource (../../node_modules/#jest/transform/build/ScriptTransformer.js:453:35)
Pipeline YAML
- task: NodeTool#0
inputs:
versionSpec: '15.x'
displayName: 'Install Node.js'
- task: Cache#2
displayName: Cache yarn packages
inputs:
key: '**/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock'
path: $(Build.SourcesDirectory)/node_modules
cacheHitVar: CACHE_HIT
- task: Yarn#3
condition: ne(variables['CACHE_HIT'], 'true')
inputs:
customRegistry: 'useFeed'
customFeed: ${{ parameters.packageFeed }}
arguments: --frozen-lockfile
displayName: 'Install NPM dependencies'
- script: yarn my-app:test
displayName: "Test My App"

Cannot test jest with monaco editor - unexpected token

Running jest on the application fails with:
Details:
/home/**/node_modules/monaco-editor/esm/vs/editor/editor.api.js:5
import { EDITOR_DEFAULTS } from './common/config/editorOptions.js';
^
SyntaxError: Unexpected token {
> 1 | import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
| ^
2 |
3 | /**
4 | * Get create function for the editor.
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (src/utils/editor-actions.js:1:1)
Application has installed packages for jest and babel-jest.
Babel config:
const presets = [
[
"#babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1"
},
useBuiltIns: "usage",
corejs: 3,
}
],
"#babel/preset-react"
];
const plugins = [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-class-properties",
"babel-plugin-styled-components"
];
module.exports = { presets, plugins };
The import statement as suggested in the docs for lazy loading modules from monaco leads to the esm folder, which jest is not familiar with.
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
By default, babel-jest would not transform node_modules and hence anything referencing the monaco-editor would error out. A possible solution is to include monaco-editor package into the compilation step by transformIgnorePatterns as mentioned in the docs
Add these to the jest config:
{
"transformIgnorePatterns": [
"node_modules\/(?!(monaco-editor)\/)"
]
}
PS: If you are using jest-dom, it might start complaining on not implmenting certain features from monaco-editor, you can mock it out with:
jest.mock("monaco-editor/esm/vs/editor/editor.api.js");
The only workaround that helped me in that issue (from here):
In folder __mocks__ create file react-monaco-editor.js with content:
import * as React from 'react';
export default function MonacoEditor() {
return <div />;
}
I have the same issue with Jest and Monaco and to make the tests pass I had to:
Add a moduleNameMapper for monaco-editor: #133 (comment)
Configure a setupTests.js like explained here: stackOverflow
I'm using:
"jest": "^24.9.0"
"babel-jest": "24.9",
"monaco-editor": "^0.20.0"
"react-monaco-editor": "0.33.0",
"monaco-editor-webpack-plugin": "^1.8.2",

Unable to implement webpack in project with node-red

I am trying to implement webpack in my project which contains node-red. However, I keep getting the following warning. Please suggest how to solve this error -
WARNING in ./node_modules/node-red/red/runtime/storage/localfilesystem/projects/git/node-red-ask-pass.sh 1:26
Module parse failed: Unexpected token (1:26)
You may need an appropriate loader to handle this file type.
> "$NODE_RED_GIT_NODE_PATH" "$NODE_RED_GIT_ASKPASS_PATH" "$NODE_RED_GIT_SOCK_PATH" $#
|
# ./node_modules/node-red/red/runtime/storage sync ^\.\/.*$ ./localfilesystem/projects/git/node-red-ask-pass.sh
# ./node_modules/node-red/red/runtime/storage/index.js
# ./node_modules/node-red/red/runtime/index.js
# ./app.js
My webpack.config.js is -
const path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'node',
externals: [nodeExternals()],
entry: './app.js',
output: {
path: path.resolve(__dirname, './output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js','.json', '.sh'],
modules: [
'node_modules'
],
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.coffee$/,
use: [ 'coffee-loader' ]
}
]
}
};
For Webpack, every file is a .js. In order to handle other extensions, like .css or .sh, you're supposed to use a loader, like you did with css-loader, that will tranform CSS rules into JS.
The issue you're facing is that you've got an import chain (./app.js -> .../index.js -> .../index.js -> .../node-red-ask-pass.sh), so Webpack will, at some point, will import a .sh file, but will throw an error because shell code is obviousouly invalid JavaScript. that is why you're seeing the error that you have.
By the way, I couldn't reproduce the issue you're facing:
npm init -y
npm i node-red
# ./node_modules/node-red/red is not a directory
So it was probably a node-red bug. Update the package to the latest version.

Resources