Search code examples
javascriptreactjstypescriptcreate-react-appava

Ava unit tests failing with TypeScript ("SyntaxError: Unexpected identifier")


I'm learning TypeScript and I created a TypeScript React app with create-react-app. It uses a separate TypeScript file, logic.ts, which in turn imports a JSON file

import pastaData from './data/users-pasta.json'

 const ParsedUserData  = pastaData.map(data => ({name: data.name, gender:data.gender,favorites: data.favorites}));

export const getPastaData = () => ParsedUserData;

It works fine. But when I run my Ava test (which for the moment does nothing)

const {getPastaData} = require( '../src/logic.ts')

describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
  });
}); 

I get the following error

/src/logic.ts:1
(function (exports, require, module, __filename, __dirname) { import pastaData from './data/users-pasta.json';
SyntaxError: Unexpected identifier

It's complaining about the 'pastaData' import here.

I set up Ava to work with Typescript (from package.json)

{

  "ava": {
    "compileEnhancements": false,
    "extensions": [
      "ts"
    ],
    "require": [
      "ts-node/register"
    ]
  }
}

And have now been trying to get Ava-ts to work. Same problem.

I think it's an issue with ts-node but changing all the linked files to 'require' is proving problematic (and TypeScript starts complaining). Is there a way to get this to work with 'ES-6' 'imports'? Or is there something else I'm missing entirely?

Any help much appreciated!


Solution

  • AVA (with TypeScript setup) compiles the TypeScript code back to JavaScript before execution.

    And NodeJS does not support esm syntax unless you are doing *.mjs.

    So you have to set your "module" to "commonjs" in your tsconfig.json:

    {
      "compilerOptions": {
        "module": "commonjs"
      }
    }