When I try to run my tests with Jest 29.7.0, it shows this error:
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.
...
Details:
D:\<redacted>\node_modules\.pnpm\uuid@8.3.2\node_modules\uuid\dist\esm-browser\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { v4 as uuid } from 'uuid';
| ^
2 |
At first glance, this would seem to be the same problem discussed on this post. However, that post is from many years ago and the conclusion appeared to be "wait until Jest supports package exports."
Jest appears to support ESModules now, the error I'm getting even references the instructional page about it. I believe I have followed the instructions on that page but yet I'm still seeing this error.
--experimental-vm-modules
flag as it said when I ran jest:node --experimental-vm-modules D:\<redacted>\node_modules\jest\bin\jest.js sample.test.ts
I didn't think I needed to do anything else (i.e. I didn't use the extensionsToTreatAsEsm
option since the file in question (index.js from uuid) has a standard extension.)
Am I overlooking something? I believe I've enabled ESM support in Jest but it still doesn't seem to like my usage of the uuid package.
Yeap you have enabled ESM support in Jest.
The reason of your error is because package.json of uuid package does not have a field "type": "module"
. (try to modify manually that file in node_modules and add type field. The error should be gone)
Jest defines package as ESM module under experimental flag either its path has .mjs extension or, in case if extension is .js, package.json should have a field "type": "module"
.
In case of uuid package path extension is .js and there is not field "type":"module" in its package.json, so Jest tries to parse it as commonJS module and meets syntax error due to export keyword.
If you really insist to use ESM in Jest then probably you may play with moduleNameMapper in jest.config to import uuid from \node_modules\uuid\dist\commonjs-browser\index.js or \node_modules\uuid\dist\index.js (instead of node_modules\uuid\dist\esm-browser\index.js which Jest currently uses)
Also have a look here - https://github.com/uuidjs/uuid/issues/678