Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest Typescript with ES Module in node_modules error - Must use import to load ES Module:

I'm trying to write a simple jest test for a 3rd party package were using that only exports an ES module. It's a wrapper around an http server.

Here is a test repo I setup (just run yarn && yarn jest to reproduce): https://github.com/jamesopti/hocuspocus-testing

No matter what config I experiment with, I still get this error when trying to run it:

 Must use import to load ES Module: /Users/j/hocuspocus-testing/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js

    > 1 | import { Server, Hocuspocus } from '@hocuspocus/server'
        | ^
      2 | import * as request from 'supertest'
      3 |
      4 | describe('Server (e2e)', () => {

Things I've tried already:

  • The Jest instructions on ES modules: https://jestjs.io/docs/ecmascript-modules

  • In Jest configuration using transformIgnorePatterns

    • transformIgnorePatterns: ['node_modules/(?!@hocuspocus/)']
  • Using Babel via babel-jest

    • modifying transform setup in Jest configuration as '^.+\.jsx?$': 'babel-jest', '^.+\.tsx?$': 'ts-jest'

    • Ran into the error You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.

    • Using .babel.config.js instead of .babelrc.js

Any ideas what I'm missing here? I thought this would be straightforward

[EDIT 1] - Added tsconfig.json and a working src/index.ts file to the example repo.

like image 230
jamis0n Avatar asked Jul 25 '21 16:07

jamis0n


3 Answers

So for anyone still hitting this, ESM configuration explained in this section of documentation :

https://kulshekhar.github.io/ts-jest/docs/guides/esm-support

{
  // [...]
  "jest": {
    "extensionsToTreatAsEsm": [".ts"],
    "globals": {
      "ts-jest": {
        "useESM": true
      }
    }
  }
}
like image 95
miki noidea Avatar answered Oct 21 '22 08:10

miki noidea


You don't have a tsconfig.json file that specifies module. Therefore it uses the default, where it transpiles all your modules to CommonJS syntax, which uses require.

If you actually look at your dist/hocuspocus-server.esm.js, you should see it using require over the ESM import syntax.

like image 40
Kelvin Schoofs Avatar answered Oct 21 '22 08:10

Kelvin Schoofs


I was having the same problem with my svelte app and testing. I ultimately traced it to having a jest.config.js and a jest.config.json in my root folder. It seems that jest does not have automatic config file resolution and was using a default configuration instead of either of my specified configurations.

like image 26
wetmarble Avatar answered Oct 21 '22 07:10

wetmarble