jestjsts-jestbabel-jest

Error running Jest and pdfjs-dist v4, not handling .mjs files


I am using the npm package pdfjs-dist@4.0.269.

When I run my code by ts-node src/pdf-reader.ts, everything works fine. But, when I try to test it using Jest, I am receiving the error

...w, __webpack_exports__updateTextLayer as updateTextLayer, __webpack_exports__version as version };
             ^^^^^^

    SyntaxError: Unexpected token 'export'

       5 |   TextItem,
       6 | } from 'pdfjs-dist/types/src/display/api.js';
    >  7 | import { getDocument } from 'pdfjs-dist';

My current configs are:

// babel.config.cjs
module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    '@babel/preset-typescript',
  ],
};
// jest.config.cjs
/** @type {import('jest').Config} */
module.exports = {
  testEnvironment: 'node',
  moduleNameMapper: { '^(\\.|\\.\\.)\\/(.+)\\.js': '$1/$2' },

  verbose: true,
  globalSetup: './test/setup/jest.setup.ts',
  globalTeardown: './test/setup/jest.teardown.ts',
  setupFilesAfterEnv: ['./test/setup/jest.setup-after-env.ts'],
  testTimeout: 15000,
};

How can I fix this error between .mjs files and Jest?


Solution

  • After pdfjs-dist version > 3 they only support ESM modules. I got this working by modifying the jest.config.js file with the following:

    transformIgnorePatterns: [
        'node_modules/(?!pdfjs-dist)',
    ],
    transform: {
        '^.+\\.(js|jsx|ts|tsx|mjs)$': 'babel-jest',
    },
    

    make sure you have installed babel-jest in your project. Before coming to this solution I tried lots of different things, so I hope this can help you.