Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Cannot use with lit-element due to ESM errors, even with transformIgnorePatterns #11783

Closed
cdrini opened this issue Aug 24, 2021 · 10 comments

Comments

@cdrini
Copy link

cdrini commented Aug 24, 2021

Version

27.0.6

Steps to reproduce

  1. Clone my minimal reproducible repo: https://github.com/cdrini/lit-jest-babel-test
  2. Run npm install
  3. Run npx jest

Expected behavior

I expect to see the tests run

Actual behavior

The test is not run with this error:

    Details:

    C:\...\lit-jest-babel-test\node_modules\lit-element\lit-element.js:57
    import { render } from 'lit-html/lib/shady-render.js';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

Despite the fact that this is file should be babel-ed by my jest.config.js

Additional context

No response

Environment

System:
    OS: Windows 10 10.0.19042
    CPU: (8) x64 Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
  Binaries:
    Node: 14.16.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.17.3 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 6.14.7 - C:\Program Files\nodejs\npm.CMD
  npmPackages:
    jest: ^27.0.6 => 27.0.6
@sigveio
Copy link
Contributor

sigveio commented Aug 24, 2021

Hi @cdrini,

Thank you for providing a reproduction. 🙂

For using ESM features such as imports, please have a look at this:
https://jestjs.io/docs/ecmascript-modules

And to use lit-element, you probably also need to use the jsdom testEnvironment.

If you would like further help or have questions on how to use Jest, please check out the following resources:

@cdrini
Copy link
Author

cdrini commented Aug 25, 2021

Gaaaah, I finally figured it out! Huge thanks to @austinkelleher and #6229 (comment) .

The issue was my .babelrc needed to be renamed to babel.config.js 😖 . Is there any way we could maybe surface this as a warning on https://jestjs.io/docs/ecmascript-modules ? Cause otherwise the fix was really simple and logical; just add lit-element/lit-html to the list of ignored transforms.

@cdrini
Copy link
Author

cdrini commented Aug 25, 2021

I kept notes while I was trying things, and didn't want it to go to waste 😅 So here's some of the stuff I tried that didn't work.

Thanks for the quick response, @sigveio ! I added testEnvironment: jsdom, but no luck.

Here's what I've tried:

1: transformIgnorePatterns to babel-ify lit and friends

( This was recommended by the error output: • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. )

Added this to jest config:

    transformIgnorePatterns: [
        "node_modules/(?!(lit-html|lit-element|lit|@lit)/)"
    ],

This didn't work; I'm not sure why? I thought this would mean that the specified node_modules would be passed through babel, but it still failed :( Am I misunderstanding this option?

2: Node ESM + babel to output esm modules

This is what's recommended by https://jestjs.io/docs/ecmascript-modules .

Following steps here, I added plugins: ["@babel/plugin-transform-modules-commonjs"] to my babel config, and ran NODE_OPTIONS=--experimental-vm-modules npx jest . Changed the wording error, but same error:

$ NODE_OPTIONS=--experimental-vm-modules npx jest
(node:23744) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  tests/SimpleGreeting.test.js
  ● Test suite failed to run

    Must use import to load ES Module: C:\...\lit-jest-babel-test\node_modules\lit-element\lit-element.js

2.1: (2), but with disabled transforms (transforms: {})

This is also recommended by https://jestjs.io/docs/ecmascript-modules . Now the test doesn't work:

$ NODE_OPTIONS=--experimental-vm-modules npx jest
(node:23852) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  tests/SimpleGreeting.test.js
  ● 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:

    C:\Users\cdrin\ProgrammingLocal\OpenLibrary\lit-jest-babel-test\tests\SimpleGreeting.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { describe, expect, test } from '@jest/globals';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1479:14)

2': 2, but with Node 16

I was using node 14 for the above; trying with latest node?

2.1'

Same error

@cakeinpanic
Copy link

Seems I have found a solution 🎉!
The key is to include babel-jest config inside of jest config and do not rely on .babelrc

added to my jest.config.js:

'transformIgnorePatterns': ["node_modules/(?!(lit-html|lit-element|lit|@lit)/)"],
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
'^.+\\.(js|jsx)$': [
	'babel-jest', {
		'presets': ['@babel/preset-env'],
		"plugins": [
			["@babel/transform-runtime"]
		]
	}]
}

versions I used:

"babel-jest": "^27.5.1",
"jest": "^26.2.2",
"@babel/preset-env": "^7.16.11",

@SimenB
Copy link
Member

SimenB commented Apr 24, 2022

You need babel.config.js to transpile node_modules.

https://babeljs.io/docs/en/config-files

@SimenB SimenB closed this as completed Apr 24, 2022
@cakeinpanic
Copy link

@SimenB thank you.
I tried few of babel config naming and placement configurations, but in monorepo(nx-based) it appeared to be not-so-simple task, so I found a solution of injecting babel right into jest config pretty usefule

@SimenB
Copy link
Member

SimenB commented Apr 25, 2022

yeah, that should also work! another option is to pass configFile: '/path/to/config.js' where you pass presets and plugins now

@cakeinpanic
Copy link

@SimenB like this?

transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
'^.+\\.(js|jsx)$': [
	'babel-jest', {
		'configFile': '<rootDir>/.babelrc'
	}]
}

@SimenB
Copy link
Member

SimenB commented Apr 25, 2022

I don't know if we do <rootDir> replacement, require.resolve('.babelrc') should work, tho

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 26, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants