Philip Frerk
Philip Frerk

Reputation: 91

Jest: SyntaxError: Unexpected token export

When I run my jasmine test with Jest I get an error:

G:\git\diamant\SpaUI\node_modules\linqts\dist\src\index.js:10
    export { default as List } from './list';
    ^^^^^^

    SyntaxError: Unexpected token export

    > 1 | import { List } from 'linqts';
        | ^
      2 | import { ReportMessageData } from './../models/report.model';
      3 | import { TranslateService } from '@ngx-translate/core';
      4 | import { Injectable } from '@angular/core';

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (src/app/feature-modules/report/services/report-message-flatten.service.ts:1:1)

I understand that I have to tell Jest to transform the code to plain Javascript, but I don't know how to do it. My jest.config.js looks as follows:

var preset = require("jest-preset-angular/jest-preset");
module.exports = {
    ...preset,
    preset: "jest-preset-angular",
    transformIgnorePatterns: ["<rootDir>/node_modules/(?!linqts)"],
    testMatch: ["**/*.test.ts"],
    globals: {
        ...preset.globals,
        "ts-jest": {
            ...preset.globals["ts-jest"],
            tsConfig: "src/tsconfig.test.json",
            isolatedModules: true
        }
    },
    moduleNameMapper: {
        '^@diamant/feature-modules(.*)$': '<rootDir>/src/app/feature-modules/$1',
    }
};

Upvotes: 3

Views: 14899

Answers (1)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

Jest doesn't support ES6 module and hence throwing this error when you directly run the test with Jest. if you want to run like that then you have to add babel.

In newer version of jest babel-jest is now automatically loaded by Jest and fully integrated

Hope this answer your question.

Adding babel in jest.

Installation
babel-jest is now automatically loaded by Jest and fully integrated. This step is only required if you are using babel-jest to transform TypeScript files.

npm install --save-dev babel-jest

Usage

In your package.json file make the following changes:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  }
}

Create .babelrc configuration file Create a babel.config.json config in your project root and enable some presets. To start, you can use the env preset, which enables transforms for ES2015+

npm install @babel/preset-env --save-dev

In order to enable the preset you have to define it in your babel.config.json file, like this:

{
  "presets": ["@babel/preset-env"]
}

Check for more details on Babel official site

Upvotes: 3

Related Questions