0

How do you run Typescript tests with Mocha for a NPM package that's mostly Javascript?

I have some Javascript/Node.js code that I'm trying to write a unittest for. Since the code does processing on audio samples recorded through the browser, I need to test it by loading wav files from the local dev filesystem.

Since that's a little easier to do in Typescript, I'd like to write my unittests in Typescript and Mocha.

However, Mocha can't seem to find even a basic stub test.

My package structure looks like:

src
    index.js
test
    test.ts
    mocha.opts

Where test.ts looks like:

import MyPackage from '../src';

describe('Simple Math Test', () => {
 it('should return 2', () => {
        assert.equal(1 + 1, 2);
    });
});

And my mocha.opts looks like:

--require ts-node/register
--recursive
--reporter spec
--ui bdd
--timeout 20000
test/**/*.ts

But when I run mocha from my project root, it outputs:

Error: No test files found

If I change my test.ts to test.js, then it finds it. How do I fix this?

Edit: I found if I run the command mocha -r ts-node/register test/test.ts, then it seems to see the Typescript test.

However, it still can't import my Javascript package:

Cannot find module '../src' or its corresponding type declarations.

import MyPackage from '../src';
Cerin
  • 60,957
  • 96
  • 316
  • 522
  • I think `test/**/*.ts` should be `tests/**/*.ts` to match the folder name, though I would expect the mocha.opts to be in the project root in this case – apokryfos Jun 19 '21 at 04:03
  • @apokryfos That's just a typo in my question. My code uses the correct name everywhere and matches the pattern in mocha.opts. – Cerin Jun 19 '21 at 04:17

1 Answers1

0

mocha by default won't run ts tests, try adding --extension js,ts

Steven Than
  • 396
  • 1
  • 2
  • 6
  • Thanks. That partially works. However, now mocha throws the error: `import MyPackage from '../src'; SyntaxError: Unexpected identifier` Even if I comment that out, it seems to choke on all the other Typescript-specific syntax, as though it's still treating everything as Javascript. I've seen projects that use Mocha to run tests written in Typescript, so Mocha definitely supports Typescript. – Cerin Jun 19 '21 at 04:18
  • I believe that is a separate issue with transpilation, `mocha` doesn't understand the ES6 `import` syntax, you'll have to use transpiling tool like babel or install the `esm` package. Relevant: https://stackoverflow.com/a/60522428/5801142 – Steven Than Jun 19 '21 at 04:22
  • Are you sure? [This package](https://github.com/peterkhayes/pitchfinder) has tests using that syntax with mocha and es5. – Cerin Jun 19 '21 at 04:42
  • It's hard to tell exactly what's going on without looking at your `tsconfig.json` and `package.json`, I've created a minimal ts-js interop boilerplate: https://github.com/steventhan/minimal-ts-js-interop-boilerplate. Can you try matching the setup? – Steven Than Jun 19 '21 at 05:18