3

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 };
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Agney
  • 18,522
  • 7
  • 57
  • 75

3 Answers3

7

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");
Agney
  • 18,522
  • 7
  • 57
  • 75
1

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 />;
}
misolo
  • 981
  • 1
  • 12
  • 16
  • I'd tried multiple solutions regarding transformIgnorePatterns and moduleNameMapper, but the only thing that's worked for me is mocking out Monaco. – Giao Tran Apr 30 '21 at 22:33
0

I have the same issue with Jest and Monaco and to make the tests pass I had to:

  1. Add a moduleNameMapper for monaco-editor: #133 (comment)
  2. 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",
lucataglia
  • 728
  • 5
  • 18