简体   繁体   中英

How can I import ES6 class modules into Jasmine for testing?

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

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. **

  • A simple solution is to use rollup

**. 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
}

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM