"Identifier 'global' has already been declared at compileFunction" error In jest tests after upgrading to monaco-editor 0.21.0 - jestjs

I upgraded my react project to use monaco-editor version 0.21.0, since then the jest tests for files where monaco-editor is being imported have started to fail with the following error:
● Test suite failed to run
/Users/omerharoon/Documents/code/packages/webapp/node_modules/monaco-editor/esm/vs/editor/editor.api.js:20
const global = self; // Set defaults for standalone editor
^
SyntaxError: Identifier 'global' has already been declared
at compileFunction (<anonymous>)
2 |
3 | import React from 'react';
> 4 | import * as monaco from 'monaco-editor';
| ^
5 | import { Resizable } from 're-resizable';
6 | import {
7 | getLanguageFromFilename,
at Runtime._execModule (node_modules/jest-runtime/build/index.js:1179:56)
at Object.<anonymous> (src/components/helpers/MonacoEditor/index.tsx:4:1)
at Object.<anonymous> (src/components/helpers/MonacoEditor/monaco_colorization.spec.tsx:6:1)
This started occurring right after the upgrade, the old version was 0.19.3 and all the tests worked fine on that version. monaco-editor-webpack-plugin was also upgraded from 1.9.0 to 2.0.0
We're importing monaco directly from
node_modules/monaco-editor/esm/vs/editor/editor.api
in order to overcome lazy loading issues.
Jest Config:
"jest": {
"modulePaths": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"**/*.{js,jsx,ts,tsx}",
"!**/*.d.ts",
"!**/node_modules/**",
"!**/public/**",
"!**/next.config.js",
"!**/server.js"
],
"setupFilesAfterEnv": [
"<rootDir>/setupTests.js"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/.next/",
"<rootDir>/public/",
"<rootDir>/config/",
"<rootDir>/next.config.js",
"<rootDir>/server.js",
"<rootDir>/build/"
],
"transform": {
"^.+\\.[jt]sx?$": "babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js"
},
"transformIgnorePatterns": [
"/node_modules/(?!monaco-editor)/",
"^.+\\.module\\.(css|sass|scss)$"
],
"moduleNameMapper": {
"^monaco-editor$": "monaco-editor/esm/vs/editor/editor.api",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"coverageReporters": [
"text",
[
"lcov",
{
"projectRoot": "../../"
}
]
]},

Upgrading to monaco-editor 0.23.0resolved the problem for me.

Related

How to build with babel and node 14?

Im trying to build my project with babel and target node 14.15.4
My .babelrc is like this
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": true
}
}
]
]
}
So i expected babel output will be compatible with current node. Unfortunately babel output keeps using require syntax instead of import so can't be run with node 14, that throws error
require("./server.js");
^
ReferenceError: require is not defined
at file:///Users/grzegorz/Projects/charts/server/dist/index.js:3:1
at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
at async Loader.import (internal/modules/esm/loader.js:166:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
Any idea what im doing wrong?
node
Type: string | "current" | true.
If you want to compile against the current node version, you can specify "node": true or "node": "current", which would be the same as "node": process.versions.node.
Example:1
{
"targets": "current"
}
example:2
{
"targets": true
}
example:3
{
"targets": "process.versions.node"
}
Alternatively, you can specify the node version in a browserslist query:
{
"targets": "node 12" // not recommended
}
Because Node.js may support new language features in minor releases, a program generated for Node.js 12.22 may throw a syntax error on Node.js 12.0. We recommend that you always specify a minor version.
{
"targets": "node 12.0"
}
Info coming from here!
The following will tell babel not to transform modules:
{
"presets": [
[
"#babel/preset-env",
{
"targets":{"node":"14"},
"modules": false,
}
]
]
}
Modules code produced in this manor will contain no inter-op glue. "modules": false is the key to this. Without it babel is very insistent on trans-piling to CommonJS compatible syntax. This option disables all module syntax transforms. This option drops the comp-ability glue and requires usage.

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",

Why decorators won't work in Jest with Babel?

I'm trying to get JavaScript decorators to work using Jest and Babel:
./package.json
[...]
"devDependencies": {
[...]
"#babel/core": "7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/plugin-proposal-decorators": "^7.3.0",
"#babel/preset-env": "^7.3.1",
[...]
"jest": "^24.1.0"
},
[...]
"scripts": {
[...]
"jest --no-cache --verbose --config ./test/unit/jest.json"
}
./test/unit/.babelrc
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
},
"modules": "commonjs",
"loose": true,
"debug": true
}
]
],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true}]
]
}
./test/unit/jest.json
{
"modulePaths": [
"<rootDir>/../../src",
"<rootDir>/../../node_modules"
],
"moduleFileExtensions": [
"js",
"json"
],
"testRegex": "\\.spec\\.js$",
"setupFiles": [
"<rootDir>/jest.js"
],
"testEnvironment": "node"
}
./test/unit/jest.js
import 'aurelia-polyfills';
import {Options} from 'aurelia-loader-nodejs';
import {globalize} from 'aurelia-pal-nodejs';
import * as path from 'path';
Options.relativeToDir = path.join(__dirname, '../../src');
globalize();
When I run yarn test I get:
yarn run v1.12.3
$ jest --no-cache --verbose --config ./test/unit/jest.json
#babel/preset-env: `DEBUG` option
Using targets:
{
"node": "11.9"
}
Using modules transform: commonjs
Using plugins:
syntax-async-generators { "node":"11.9" }
syntax-object-rest-spread { "node":"11.9" }
syntax-json-strings { "node":"11.9" }
syntax-optional-catch-binding { "node":"11.9" }
Using polyfills: No polyfills were added, since the `useBuiltIns` option was not set.
console.error internal/process/next_tick.js:81
{ SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
at Parser.raise ([...]/node_modules/#babel/parser/lib/index.js:3831:17)
at Parser.expectOnePlugin ([...]/node_modules/#babel/parser/lib/index.js:5158:18)
at Parser.parseDecorator ([...]/node_modules/#babel/parser/lib/index.js:7428:10)
at Parser.parseDecorators ([...]/node_modules/#babel/parser/lib/index.js:7410:30)
at Parser.parseStatement ([...]/node_modules/#babel/parser/lib/index.js:7245:12)
at Parser.parseBlockOrModuleBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7812:25)
at Parser.parseBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7799:10)
at Parser.parseTopLevel ([...]/node_modules/#babel/parser/lib/index.js:7181:10)
at Parser.parse ([...]/node_modules/#babel/parser/lib/index.js:8660:17)
at parse ([...]/node_modules/#babel/parser/lib/index.js:10643:38)
pos: 362,
loc: Position { line: 10, column: 0 },
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
console.log test/unit/resources/elements/price.spec.js:25
SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
FAIL test/unit/resources/elements/price.spec.js (5.467s)
ProductPrice
✕ should render current (5008ms)
● ProductPrice › should render current
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
18 | });
19 |
> 20 | it('should render current', done => {
| ^
21 | component.create(bootstrap).then(() => {
22 | const currentElement = document.querySelector('.current');
23 | expect(currentElement.innerHTML).toBe('');
at Spec (../../node_modules/jest-jasmine2/build/jasmine/Spec.js:92:20)
at Suite.it (resources/elements/price.spec.js:20:5)
● ProductPrice › should render current
Cannot call ComponentTester.dispose() before ComponentTester.create()
27 |
28 | afterEach(() => {
> 29 | component.dispose();
| ^
30 | });
31 | });
at ComponentTester.Object.<anonymous>.ComponentTester.dispose (../../node_modules/aurelia-testing/dist/commonjs/component-tester.js:66:19)
at Object.dispose (resources/elements/price.spec.js:29:19)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 6.389s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
What I'm doing wrong?
A good hint comes with the error message:
[...]
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
The Babel integration of Jest tooks the .babelrc in the first place, for every other file reached from the test it searched only in the project root. In this case the Babel configuration was in ./test/unit.
So putting .babelrc into the project root folder is one possible fix (but not the best). More approaches can be found here.

Jest Is Not Transpiling ES6 Modules In Test (SyntaxError: Unexpected token export)

I'm at a boiling point with getting Jest to understand ES6 modules import/export syntax and it is hindering my project development progress. My project structure is the following:
root module
org-domain (ES6)
org-services (ES6)
react-ui-module (React via CRA2)
org-services has a local path dependency on org-domain in its package json:
// in org-services package.json
"dependencies": {
"#org/domain": "file:../org-domain",
},
My .babelrc in org-services is the following:
{
"env": {
"test": {
"presets": ["#babel/preset-flow", "#babel/preset-env"]
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
},
"presets": [
"#babel/preset-flow",
["#babel/preset-env", {
"targets": {
"esmodules": true
}
}]
],
"plugins": [
["module-resolver", {
"root": ["./node_modules/#org/domain"],
"alias": {
"#org/constants": "./node_modules/#org/domain/src/constants",
"#org/contracts": "./node_modules/#org/domain/src/request-contracts"
}
}]
]
}
I do not know if the problem is due to how I am including my dependencies so I'm going to add the finer details of anything related to my import/export of these modules for the sake of clarity.
In the implementation files of org-services I am importing org-domain using npm scoped syntax like so: import ... from '#org/domain
Here are some observations I have:
In local development, when I try to reference click #org/domain, instead of being directed to org-services/node_modules/#org/domain I get redirected to the actual relative directory location which is root/org-services. I believe Jest ignores node_modules (correct me if I am wrong) but in my jest.config.js for org-services, I have:
collectCoverage: true,
coverageDirectory: 'coverage',
coveragePathIgnorePatterns: [
'/node_modules/'
],
moduleDirectories: [
'src',
'node_modules'
],
moduleFileExtensions: [
'js'
],
transform: {
'^.+\\.js$': 'babel-jest'
},
transformIgnorePatterns: [
'node_modules/(?!#org/domain)$'
]
To my understanding, everything should just work right now with all the configuration I have with respect to setting the plugin #babel/plugin-transform-modules-commonjs in test (within .babelrc) and including the '^.+\\.js$': 'babel-jest' instruction under the transform key in jest.config.js located under org-services -- but it does not.
I have tried every single thing I could find online with respect to this issue with no success. I have not gotten anywhere since and my patience is lost with this testing framework and the lack of support for ES6. It should not be this hard, so clearly I am doing something wrong here. Please advise.
Update 1
Found another SO post that is a mirror of this situation I am in.
Jest fails to transpile import from npm linked module
Unfortunately, the provided solution does not work for my case.
After upgrading from #babel/xyz: 7.0.0 to 7.1.2 I started getting an error regarding "import"
Jest encountered an unexpected token
<snip>
Details:
C:\....\SstcStrategy.test.js:2
import sequelizeFixtures from 'sequelize-fixtures';
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
To fix this I had to add #babel/plugin-transform-modules-commonjs as you mention in your question.
My babel.config.js now looks like this:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: '8.10',
},
debug: false,
},
],
],
ignore: ['node_modules'],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-transform-modules-commonjs',
// Stage 2
['#babel/plugin-proposal-decorators', { legacy: true }],
'#babel/plugin-proposal-function-sent',
'#babel/plugin-proposal-export-namespace-from',
'#babel/plugin-proposal-numeric-separator',
'#babel/plugin-proposal-throw-expressions',
// Stage 3
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-syntax-import-meta',
['#babel/plugin-proposal-class-properties', { loose: false }],
'#babel/plugin-proposal-json-strings',
],
};
Also BTW you don't need to define babel-jest transform in jest.config.js as this is the default setting.
Hope this helps

Use Jest and spread operator without babel?

Is it possible to use the spread operator in code with Jest and without babel if the node engine is 8+?
I am dropping support for Node.js <8 in my app and assumed I could remove all babel dependencies and transpiling from package.json, however npm run jest fails immediately with these types of errors:
FAIL test/workers/repository/onboarding.spec.js
● Test suite failed to run
/Users/me/project/lib/workers/repository/onboarding.js: Unexpected token (13:17)
11 |
12 | async function createOnboardingBranch(inputConfig) {
> 13 | let config = { ...inputConfig };
| ^
Is there any way to get Jest to work without needing to add back all the babel dependencies and configuration?
Node.js version: 8.9.0
Jest version: 20.0.4
jest config in package.json:
"jest": {
"cacheDirectory": ".cache/jest",
"coverageDirectory": "./coverage",
"collectCoverage": true,
"collectCoverageFrom": [
"lib/**/*.js"
],
"coverageReporters": [
"json",
"lcov",
"text-summary"
],
"setupTestFrameworkScriptFile": "./test/chai.js"
},
Edit:
I have been able to narrow my babel configuration down to just one plugin: babel-plugin-transform-object-rest-spread and configure babel in package.json like so:
"babel": {
"plugins": [
"transform-object-rest-spread"
]
},
Taking this out or attempting to use babel-preset env causes Jest to fail on the spread operator again.

Resources