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

Viewed 11415

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.

3 Answers

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.

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.

Related