Reputation: 91
I want to unit test some ES6 classes that are stored as modules. However, when I try to run my tests, import
triggers an error message: Cannot use import statement outside a module
which means I can't test my modules.
All the Jasmine examples use the old ES5 syntax with classes defined as function
s using the modules.export
and then imported using the require
function. I've found websites such as this where they seem to use the ES6 and import { module } from 'path'
syntax, but I have no idea why this works and why mine doesn't? Is it because I'm not testing using a headless browser? It is because Jasmine doesn't support this functionality natively and I need some other package? Is it because I need to use jasmine-node
in some specific way to get it to work? Should I not be using ES6 classes at all?
As its probably obvious I'm a beginner to node and javascript but I wouldn't have thought that just testing the functionality of a class would be this difficult so if anyone could give me some guidance on how to accomplish testing a class module in Jasmine I would be really grateful.
For example I have a module.
// src/myClass.mjs
export class MyClass {
constructor() { }
}
I have a simple Jasmine unit test.
// spec/myClassSpec.js
import { MyClass } from '../src/myClass.mjs'
describe('my class', function() {
var myClassInstance
beforeEach(function() {
myClassInstance = new MyClass()
})
it('is an instance of MyClass', function() {
expect(myClassInstance).toBeInstanceOf(MyClass)
})
})
Upvotes: 9
Views: 4026
Reputation: 22455
Upgrade Node to version 13 or higher. Enable ECMAScript modules in Node by setting "type" field to "module" in package.json:
{
"type": "module",
...
}
Upvotes: 0
Reputation: 27
I may be late to answer however using "import" statement in Nodejs is not as simple as it looks. There are few main differences between require and import (like being async) thus one can not be simply converted into another. **
**. Once you have completed your module your can use rollup to bundle this module as a commonjs file. That file can then be used for testing.
To install rollup
npm install rollup --save-dev
After rollup in installed you need to add following commands to the script of "package.json" file
"dist": "rollup -c"
You need to have a rollup.config.js file in the root folder of your application. The content of rollup.config.js are:
import { rollup } from "rollup";
export default {
input: './index.js',
output: {
file: 'dist/index.js',
format: 'cjs' //cjs stands for common js file
}
};
Upvotes: 2