Reputation: 1223
I'm learning to test my JavaScript with Jest. I have a basic project that's setup like this:
/
/src
myClass.js
/tests
myClass.test.js
package.json
The code looks like this:
myClass.js
export class MyClass {
constructor() {
this.result = null;
}
calculate() {
this.result = 1;
return this.result;
}
}
myClass.test.js
import { MyClass } from '../src/myClass';
test('Calculate', () => {
let myObject = new MyClass();
let result = myObject.calculate();
expect(result).toBe(1);
});
package.json
{
"name": "sample-project",
"version": "0.0.1",
"type":"module",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "jest"
},
"dependencies": {
"vue": "^3.2.16",
"vue-router": "^4.0.11"
},
"devDependencies": {
"@vitejs/plugin-vue": "^1.9.3",
"jest": "^27.3.1",
"vite": "^2.6.4",
"vite-plugin-html": "^2.1.1",
"vite-plugin-singlefile": "^0.5.1"
}
}
When I run my tests using npm run test
, which just executes jest
, I receive an error that says: SyntaxError: Cannot use import statement outside a module
.
What am I doing wrong? How do I test MyClass
from Jest?
Upvotes: 0
Views: 781
Reputation: 711
Please follow the Babel
sections in the Jest's Getting Started Guide
Simply run:
yarn add --dev babel-jest @babel/core @babel/preset-env
and create a babel.config.js
file in the project root directory with the following content:
// babel.config.js
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
FYI: Jest is using virtual Node environments under the hood. If I remember correctly the oldest supported Node version is 10. Therefore you need to configure a source code transformer like Babel if you want to use ES6 features. (Source)
Upvotes: 2