0

I have a typescript project with some mocha tests, that start like so:

import { assert } from "chai";
import "@material/mwc-ripple"; //I want to test a script that uses this

describe("simple test", () => {
    it("works", () => {
    assert.isOk(true)
  });
});

In the mocha tsconfig.test.json, if I set "module": "esnext" I get the following error:

/home/ec2-user/environment/frontend/test-mocha/common/datetime/aaa_aaa_test.ts:1
import { assert } from "chai";
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    ...

But if I set it to "module": "commonjs" I get this error:

/home/ec2-user/environment/frontend/node_modules/@material/mwc-ripple/mwc-ripple.js:1
import { __decorate } from "tslib";
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    ...

What is going on and how should I fix it?

Matthew
  • 10,361
  • 5
  • 42
  • 54
  • It doesn't look like you're compiling typescript modules. It looks like you're trying to run typescript files directly in mocha – slebetman May 08 '20 at 05:28
  • I see that mocha's preference is to use `commonjs`: https://github.com/mochajs/mocha-examples/tree/master/packages/typescript so why does the nested import still fail? – Matthew May 08 '20 at 06:37
  • It's not just that. Mocha runs on javascript. It doesn't understand typescript by default. If you use mocha with Node 14 for example you can use the import statement but note that node's import statement follows the ES6 module standard which does not comply with how Typescript implements the import statement (specifically you need to require a cjs module and import an mjs module). I've never used typescript with mocha but a few seconds of googling led me to ts-mocha which you might be interested in checking out – slebetman May 08 '20 at 07:07
  • I'm using ts-node as per the mocha typescript example. I think the issue is with the import statement. See my answer below. – Matthew May 08 '20 at 07:25

1 Answers1

0

Aha I think I've found the culprit!

If I change

import "@material/mwc-ripple";

to

import { Ripple } from "@material/mwc-ripple";

It clears the error. I'm guessing the different import syntax hints to ts-node that the imported file is to be parsed as javascript or typescript. Maybe?

Matthew
  • 10,361
  • 5
  • 42
  • 54