My package imports an ESM package called c2pa
. When I run jest
I get an error like this:
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
I believe the docs for ECMAScript Modules are for if my package is ESM, but I am having an issue with a dependency.
I also updated my Jest config to try out transformIgnorePatterns
override mentioned in the error and Jest gives an error: "SyntaxError: Unexpected token export".
const babelConfig = require('../../babel.config.json');
module.exports = {
preset: 'ts-jest/presets/js-with-babel',
testEnvironment: 'jsdom',
roots: ['tests', 'src'],
collectCoverageFrom: ['src/**/*.ts'],
coveragePathIgnorePatterns: ['__mocks__'],
moduleNameMapper: {
'^uxp$': '<rootDir>/../../dependency-mocks/uxp.js',
},
transformIgnorePatterns: ['/node_modules/(?!c2pa)/'],
globals: {
'ts-jest': {
babelConfig,
},
tsConfig: {
declaration: false,
},
PLUGIN_REV: '__pluginRev__',
},
setupFilesAfterEnv: ['./tests/test.setup.js'],
};
I also tried a babel plugin that is mentioned in the linked SO question.
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
},
I'm not sure if there's any other jest of babel config I might be missing here. Clearly something is wrong!
Aside from ignorePattern, I also updated preset:
preset: 'ts-jest/presets/js-with-ts',
The babel config changes were not necessary at all.