javascriptmocha.jschai

Chai Unexpected token when importing


So i have this very very simple dummy test:

import {expect}  from 'chai';

describe('calculate', function () {
    it('add', function () {
        let result = 2 + 5;
        expect(result).equal(7);
    });
});

Here i get the following error when i run it:

(function (exports, require, module, __filename, __dirname) { import { expect } from 'chai';
                                                                     ^

SyntaxError: Unexpected token {

Can anyone tell me whats going on?


Solution

  • You need to transpile your code to use commonjs imports. You can use babel for such a task, see the docs https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs.

    Via cli you can run babel --plugins @babel/plugin-transform-modules-commonjs script.js and then simply run your script.

    If you don't want to use either transpilation (using babel or whatever) or commonjs you could use a loader such as esm: https://www.npmjs.com/package/esm.

    From the docs, after running yarn add esm you can just node -r esm main.js.