Jasmine testing dependencies: Cannot use import statement outside of a module

1.1k views Asked by At

I know there are plenty of 'Cannot use import statement outside a module' threads but none for jasmine that I've found. I have a client side application using Preact, Parcel and Openlayers. Most of my code sits in a Map.js module and I'm trying to setup Jasmine to do some testing of the functions within.

I've installed jasmine (and later on jasmine-es6), babel-cli, babel-present-env, babel-preset-es2015 but whenever I run the jasmin command the tests fail on importing dependencies. My spec files are able to import my Map.js, but then fail to import the dependencies of Map.js e.g. Import ...node_modules\ol\control\MousePosition.

my json.package has type:module.

my .babelrc file:

{
    "presets": ["@babel/preset-env"]
}

jasmine.json:

  "spec_dir": "/spec",
  "spec_files": [
    "**/*[sS]pec.js"
  ],
  "helpers": [
    "../node_modules/@babel/register/lib/node.js"
  ],
  "stopSpecOnExpectationFailure": false,
  "random": true
}

Example spec:

import MapMod from "../src/Map"

describe('Testing map initialization', () => {
    
    beforeEach(() => {
        // I've tried require() here but get the same error
    });

    it('Should not throw errors', function () {
        expect(MapMod.initMap).not.toThrow();
    });
})

I'm stumped. Can anyone help?

1

There are 1 answers

0
mmcnickle On

The

"helpers": [
  "../node_modules/@babel/register/lib/node.js"
]

config doesn't seem to work for me on later versions of @babel/register (> 7.12.1).

Instead, I created a new helper called babel.js, that contains the following:

require('@babel/register')

and included that as a helper instead of ../node_modules/@babel/register/lib/node.js:

  "helpers": [
    "spec/helpers/babel.js"
  ]