🧩 How I Solved Jest "Unexpected token 'export'" Error (When Testing a Pure ESM Package)

Recently, while writing unit tests for our React application, I stumbled into one of those classic "wait... what just happened?" developer moments.

Everything was going great, and then β€” boom πŸ’₯ β€” my npm run test exploded with this beauty:

SyntaxError: Unexpected token 'export'

At first, I thought maybe I had a typo somewhere.
But no.
It turned out the real culprit was something far sneakier: a pure ESM package.

In this post, I’ll walk you through:

  • How I ran into this problem

  • What a pure ESM package actually is (and why it matters)

  • Two simple ways to fix it: mocking or transforming

  • Lessons learned (aka, how not to lose your mind)

Let's dive in πŸš€

πŸ› The Problem: Jest Hates Pure ESM (Without Help)

The error popped up when I tried importing the export-to-csv library inside my code:

import { mkConfig, generateCsv, download } from 'export-to-csv';

When I ran tests with Jest, I got:

node_modules/export-to-csv/output/index.js:4
export { mkConfig, generateCsv, download };
^^^^^^

SyntaxError: Unexpected token 'export'

At first glance, it felt like Jest was somehow unable to understand a normal JavaScript file.
Which made no sense... until I realized:

πŸ‘‰ export-to-csv recently switched to a Pure ESM package.

And Jest?
Well, Jest is still mostly tuned for CommonJS out of the box β€” especially if you haven't customized the config.

✍️ Short Note: What the Heck Is a "Pure ESM" Package Anyway?

Here's the fun version:

Traditionally, Node.js packages used CommonJS (require(), module.exports) β€” the "old school" way of sharing code.

ESM (ECMAScript Modules) is the "modern" way (import/export) that's now officially supported in Node.js and browsers.

A pure ESM package only uses import/export, doesn't ship any CommonJS fallback, and often has .mjs files or type: "module" in its package.json.

Why it matters:
Pure ESM packages break tools that expect CommonJS, unless you configure them to understand ESM syntax.

Jest, unless tweaked, expects CommonJS. Hence the crash.

πŸ› οΈ Solution 1: The Quick and Practical Fix β€” Mock It!

If you don’t need to deeply test the library itself (only your own code),
the easiest fix is to simply mock the ESM module.

In my case, I updated my setupTests.ts (or you could do it inside the specific test file):

jest.mock('export-to-csv', () => ({
  mkConfig: jest.fn(() => ({})),
  generateCsv: jest.fn(() => ''),
  download: jest.fn(() => {}),
}));

βœ… This way, when my code tries to use generateCsv, it just calls a harmless mock instead of crashing.

βœ… Jest never has to try parsing the ESM file.

βœ… I can write my unit tests peacefully.

πŸ”₯ Solution 2: The Advanced Fix β€” Tell Jest to Transpile ESM Files

If you really want to run the actual code (not mock it),
you'll need to make Jest transform the ESM package properly.

Here’s how:

Step 1: Update transformIgnorePatterns

In your package.json Jest config (or jest.config.js),
make sure export-to-csv is excluded from ignore patterns:

"transformIgnorePatterns": [
  "node_modules/(?!export-to-csv)/"
]

Normally, Jest skips all node_modules,
but now it will process export-to-csv through your transformer (like babel-jest or ts-jest).

Step 2: (Optional) Use Babel to Handle ESM

If you're using Babel, you might need to adjust .babelrc or babel.config.js:

module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
};

This ensures Babel can understand ESM import/export syntax.

⚠️ Warning:

  • This method is slightly heavier.

  • Can cause longer build/test times.

  • Might need fine-tuning based on library dependencies.

In my case, mocking was faster and good enough.

πŸ“š Lessons Learned

  • Many modern libraries are moving to pure ESM.
    (And it's a good thing long-term! πŸš€)

  • Jest needs extra help to deal with ESM packages.

  • If you just need to unit test your own code, mocking external libraries is the cleanest way.

  • If you truly need the library code tested, be ready to tweak Jest config and maybe Babel.

🎯 Final Thoughts

Running into weird errors like "Unexpected token 'export'" feels scary at first...
but with a little digging, you realize it’s just tools catching up with modern JavaScript.

The real superpower is knowing when to mock something and when to transform it properly.

Hopefully, this post saves you a few hours of debugging next time you see your terminal scream in horror! πŸ˜„

If you faced similar issues or found even cooler fixes,
I'd love to hear from you β€” drop a comment or connect!

βœ… TL;DR (For Speed Readers)

ProblemSolution
Jest error "Unexpected token 'export'" when importing ESM packagesMock the package OR tweak Jest transform settings
Best first fixjest.mock() the ESM package
If you need real codeUpdate transformIgnorePatterns and maybe use Babel
0
Subscribe to my newsletter

Read articles from Dhanraj Pai Raiturkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dhanraj Pai Raiturkar
Dhanraj Pai Raiturkar

I'm a Software Engineer 2 at Blue Yonder, working primarily with JavaScript, TypeScript, React, Node.js, and MongoDB. With over 3 years of experience, I've built scalable frontend and backend solutions, including working with AWS serverless technologies like Lambda and DynamoDB in my previous role. I hold a Bachelor's in Computer Applications (BCA) and a Master's in Computer Applications (MCA), and I'm passionate about building clean, performant applications and continuously learning new things in the world of web development.