Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running tests .mjs / ESM on Node using Jasmine or any other alternative

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)?

like image 293
Matías Fidemraizer Avatar asked Dec 15 '17 12:12

Matías Fidemraizer


People also ask

Does Nodejs support ESM?

In May, 2020, Node. js v12. 17.0 made ESM support available to all Node. js applications (without experimental flags).

Can jasmine be integrated with node js?

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.


1 Answers

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()
like image 78
Matías Fidemraizer Avatar answered Sep 23 '22 22:09

Matías Fidemraizer