Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 358
Andry Avatar asked Sep 11 '25 11:09

Andry


2 Answers

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.

like image 177
Kraylog Avatar answered Sep 13 '25 01:09

Kraylog


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.

like image 45
felixmosh Avatar answered Sep 13 '25 01:09

felixmosh