My Node-based project is implemented using native ES module support on Node thanks to the --experimental-modules
CLI switch (i.e. node --experimental-modules
).
Obviously, when I run a spec using Jasmine node --experimental-modules ./node_modules/jasmine/bin/jasmine
I get the following error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
Is it ever possible to use Jasmine using ES modules in Node?
If not, is there any alternative to don't use a framework (e.g. running tests with npm
scripts)?
In May, 2020, Node. js v12. 17.0 made ESM support available to all Node. js applications (without experimental flags).
In order to test a Node. js application, the jasmine framework needs to be installed first. This is done by using the Node package manager. The test code needs to be written in a separate file, and the word 'spec' should be appended to the file name.
It was easier than I thought.
It's just about calling a file which you might call run.mjs
as follows:
node --experimental-modules ./run.mjs
The whole file would look like this:
jasmine.mjs
:
import Jasmine from "jasmine"
import JasmineConsoleReporter from "jasmine-console-reporter"
const jasmine = new Jasmine()
jasmine.loadConfigFile( "./support/jasmine.json" )
jasmine.env.clearReporters()
jasmine.addReporter( new JasmineConsoleReporter( {
colors: true,
cleanStack: true,
verbosity: 4,
listStyle: 'indent',
activity: false
} ) )
export default jasmine
And you would add specs as follows in separate files:
import jasmine from './my-project/spec/jasmine.mjs'
jasmine.env.describe('Foo', () => {
jasmine.env.it('Bar', () => {
// Expects, assertions...
})
})
Finally, you would run jasmine
importing both configured jasmine
instance and specs:
import jasmine from './my-project/spec/jasmine.mjs'
import someSpec1 from './my-project/spec/someSpec1.mjs'
import someSpecN from './my-project/spec/someSpecN.mjs'
someSpec1()
someSpecN()
jasmine.execute()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With