Andry
Andry

Reputation: 16845

How to write unit tests supporting Javascript 6 modules

My Javascript codebase is based on new ES6 Modules.

So I have Javascript files like this for example:

export class MyClass {
  constructor() {
    this.list = [];
  }

  add(el) { this.list.push(el); }
}

As a module, I import this file in other Javascript files like this:

import * as lists from "./myclass";

And inside an HTML page, the following syntax has to be used:

<script src="myclass.js" type="module"></script>

Unit testing

I need a framework for testing my code. The problem is that I am using Javascript 6 modules, so modern frameworks like karma have problems as they import the files not as modules:

module.exports = function(config) {
  config.set({
    files: [
      'src/**/*.js',
      'test/**/*.js'
    ],
    ...
  })
}

Above is an example of karma.conf.js. In the specific case of Karma, the runner will not import the files as modules, thus the injection in page fails.

What unit test frameworks can I use for testing Javascript 6 modules?

Upvotes: 4

Views: 2047

Answers (3)

backspaces
backspaces

Reputation: 3942

I'm not sure Jest actually supports modules, right? I.e. I want my test files .. those with the assertions .. to be able to import modules which also import other modules.

It seems the best you can do with node based testing frameworks, with I think may be all of them, is us pretty awful babel/webpack stunts which I'd really prefer not to use.

Headless Chrome certainly seems to be interesting, as does Puppeteer

Upvotes: 0

felixmosh
felixmosh

Reputation: 35513

You can check out Jest, it's Facebook's test framework that allows you to run your tests on Node (with JSDOM).

It runs your tests in parallel and without browser, therefore suppose to be much faster.

Upvotes: 1

Kraylog
Kraylog

Reputation: 7553

I'm using a combination of Mocha and Babel - Babel transpiles the ES6 modules to code Mocha can work with, and so you can use import in the test files.

To run mocha with the Babel transpiler:

mocha --compilers js:babel-core/register --recursive test/*

I'm pretty sure other frameworks have a similar solution.

Upvotes: 2

Related Questions