I was trying to use jest for testing my module files and got encountered to error, I looked for online help, tried running test by changing it to a cjs file but wasn’t successful.
The error I encountered:
FAIL tests/sum.test.cjs
● Test suite failed to run
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.
more specifically
Details:
<edited_path>event-management-systemtestssum.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import sum from '../sum.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:1495:14)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.227 s
Ran all test suites.
The files I used to test was
sum.js
const sum = (a, b) => {
return a + b;
};
export default sum;
sum.test.js
import sum from '../sum.js';
describe('sum module', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
Please help me with this specific error
Edit:
I have tried out
Changing file types to .mjs files
or
Use require syntax instead of import.
and
using .cjs file time for the test file.
package.json
{
"name": "event-management-system",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"jest": {
"testMatch": [
"**/*.test.js"
]
},
"scripts": {
"test": "npx jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
},
"devDependencies": {
"jest": "^29.5.0"
}
}
3
Answers
Thank you, everyone, for considering, the issue was solved by adding the script for testing in
package.json
file, as:It is described here, however, it is experimental and may change over time.
A couple of things to try:
In your
package.json
add thisor
Change your file types to
.mjs
filesor
Use
require
syntax instead ofimport
.you can see some of these solutions here:
"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6
This is a problem with jest for handling ECMAScript Modules, and the updates are experimental. If you want to use jest for any project where you have described
"type": "module"
then have look to this documentation.Your problem can be fixed by adding a testing script provided below in the
package.json
file,