Chevrotain / chevrotain

Parser Building Toolkit for JavaScript
https://chevrotain.io
Apache License 2.0
2.44k stars 199 forks source link

Getting Cannot find module 'chevrotain' error when running unit test using jest #1997

Closed Jayakrishnan-MS closed 8 months ago

Jayakrishnan-MS commented 8 months ago

Greetings,

Recently I converted my react project to ESM. Everything works fine until it comes to unit testing. I am using chevrotain latest version ^11.0.0 in my project. While running unit test using jest I am getting the following error:

$ npm run test tokens.test.ts

@mo/licit-citation@0.1.8 test jest --coverage "tokens.test.ts"

FAIL src/tokens.test.ts ● Test suite failed to run

Cannot find module 'chevrotain' from 'src/tokens.ts'

Require stack:
  src/tokens.ts
  src/tokens.test.ts

> 1 | import {createToken, CustomPatternMatcherReturn, IToken} from 'chevrotain';
    | ^
  2 | import {NF} from './Constants';
  3 |
  4 | export const DSEP = '//';

  at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:427:11)
  at Object.<anonymous> (src/tokens.ts:1:1)
  at Object.<anonymous> (src/tokens.test.ts:5:1)

The test runs fine when using the older version (^10.0.0) of chevrotain. I think the issue is related to the latest version of chevrotain as no other modules have this issue.

msujew commented 8 months ago

@Jayakrishnan-MS Are you sure that jest is running the code as ESM? The import in line 2 doesn't look like an ESM import:

import {NF} from './Constants';

ESM requires to add the file extension to the import, unlike CJS which just appends it if it's missing. That would also explain why Chevrotain 10 was working, which delivered a CJS package.

Jayakrishnan-MS commented 8 months ago

Yeah, you are right. Jest is running the code in CJS even though my project is in ESM. So the error occurred since Chevrotain 11 is ESM-only and jest tries to run it in CJS. So I guess the workaround is to enable ESM support in Jest by running Node.js with the --experimental-vm-modules like this: { "scripts": { "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" } } But this will affect my other imports. So I'll stick on with the Chevrotain 10 in my project. Thanks for the suggestion!!

kokokenada commented 6 months ago

I couldn't make jest work with 11. Downgrading to 10.5 for now

bd82 commented 6 months ago

Looks like Jest support for ESM relies on experimental APIs

loicknuchel commented 4 months ago

Same here, downgrading to 10.5 to make it work. If you find a fix, please let us know :pray:

swami-sanapathi commented 3 months ago

yes, downgrading to 10.5.0 works fine, but with 11.0.3 tests failing

bd82 commented 3 months ago

You could probably bundle Chevrotain as a commonJS module in your project's postinstall script and consume it via the bundled version to work around ESM compatibility issues.