Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest test fails with Unexpected token, expected ";"

I have a Node project using Typescript and Jest. Currently I have this project structure

enter image description here

With this tsconfig.json file

  "compilerOptions": {
    "target": "ES2017",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }

this jest.config.js file

module.exports = {
  clearMocks: true,
  coverageDirectory: "coverage",
  testEnvironment: "node",
};

and this package.json file

{
  "scripts": {
    "start": "node dist/App.js",
    "dev": "nodemon src/App.ts",
    "build": "tsc -p .",
    "test": "jest"
  },
  "dependencies": {
    "commander": "^3.0.1"
  },
  "devDependencies": {
    "@types/jest": "^24.0.18",
    "@types/node": "^12.7.4",
    "jest": "^24.9.0",
    "nodemon": "^1.19.2",
    "ts-jest": "^24.0.2",
    "ts-node": "^8.3.0",
    "typescript": "^3.6.2"
  }
}

I created a test file in my tests directory

import { App } from '../src/App';

describe('Generating App', () => {
  let app: App;

  test('It runs a test', () => {
    expect(true).toBe(true);
  });
});

but unfortunately I get a syntax error

SyntaxError: C:...\tests\App.test.ts: Unexpected token, expected ";" (5:9)

at my app variable. It seems the test runner is not able to understand Typescript code. How can I fix my configuration to support Typescript in test files for Jest?

like image 502
hrp8sfH4xQ4 Avatar asked Sep 13 '19 09:09

hrp8sfH4xQ4


1 Answers

Try to add typescript extension in jest config :

module.exports = {
  roots: ['<rootDir>'],
  transform: {
    '^.+\\.ts?$': 'ts-jest'
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
  moduleFileExtensions: ['ts', 'js', 'json', 'node'],
  collectCoverage: true,
  clearMocks: true,
  coverageDirectory: "coverage",
};

And then load the jest config in your package.json test script :

"scripts": {
    "test": "jest --config ./jest.config.js",
    ...
  },
like image 114
Putxe Avatar answered Oct 22 '22 09:10

Putxe