Jest test of React application with TypeScript SyntaxError... Unexpected reserved word 'interface'

javaface

I have a simple react application (not create-react-app) with TypeScript. It runs without problems, but tests fail with error "SyntaxError... Unexpected reserved word 'interface'". How to make jest recognize interface syntax from TypeScript? I broke my head trying different solutions.

Component

    import React from 'react';
    import {  Switch, Route } from 'react-router-dom';
    import * as p from '@/config/paths';
    import Login from "@/react/components/authentication/Login";
    import Register from "@/react/components/authentication/Register";
    import MainLayout from "@/react/fragments/MainLayout";

interface Props {
    test: string,
    onLogin: ()=> void
}

const Auth: React.FC<Props> = (...props) =>(
    <>
        <MainLayout>
            <h1>Authentication</h1>
            <Switch>
                <Route path={p.pathLogin()}>
                    <Login />
                </Route>
                <Route  path={p.pathRegister()}>
                    <Register/>
                </Route>
            </Switch>
        </MainLayout>
    </>
)

export default Auth;

Test

   import React from "react";
   import Auth from "@/react/pages/Auth";
   import { createMounted } from "@/config/testConfig";

const requiredProps = {
    test:"Test",
    onLogin: jest.fn()
};

describe("Home Snapshot", () => {
    const { wrapper } = createMounted(<Auth {...requiredProps} />);

    it("default snapshot", () => {
        expect(wrapper).toMatchSnapshot();
    });
});

Jest configuration in package.json

  "jest": {
        "automock": false,
        "cacheDirectory": ".cache/jest",
        "setupTestFrameworkScriptFile": "<rootDir>/__tests__setup.js",
        "snapshotSerializers": [
          "jest-serializer-html"
        ],
        "coverageDirectory": "__tests__coverage",
        "collectCoverageFrom": [
          "src/**/*.{js,jsx}"
        ],
        "moduleNameMapper": {
          "\\.(jpg|jpeg|png|gif|svg|pdf|ico|mp4|obj)$": "<rootDir>/__mocks__/fileMock.js",
          "\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js"
        }
      },

.babelrc

{
  "presets": [
    "@babel/preset-react",
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-syntax-dynamic-import",
    [
      "module-resolver",
      {
        "alias": {
          "@": "./src"
        }
      }
    ]
  ]
}

__tests__setup.js

import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
global.fetch = require("jest-fetch-mock");

Enzyme.configure({ adapter: new Adapter() });

tsconfig.json

    {
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es6",
    "jsx": "react",
    "allowJs": true,
    "esModuleInterop": true,
    "noImplicitThis": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@/*":["src/*"]
    }
  },
  "include": [
    "./src/**/*"
  ]
}

Webpack

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const {CleanWebpackPlugin} = require("clean-webpack-plugin");
    const fs = require("fs");

    const ENTRY_JS = "js";
    const ENTRY_CSS = "css";

    module.exports = {
        entry: {
            [ENTRY_JS]: "./src/index.tsx",
            [ENTRY_CSS]: "./src/assets/scss/root.scss"
        },
        output: {
            filename: "[name].[chunkhash].js",
            chunkFilename: "[name].[chunkhash].js",
            path: path.resolve(__dirname, "dist"),
            publicPath: "/"
          },
          resolve: {
              extensions: ['.ts', '.tsx', '.js', '.json', '.scss'],
              alias: {
                  "@": path.resolve(__dirname, "src/")
              }
          },
        module: {
            rules: [
                {
                    test: /\.ts(x?)$/,
                    exclude: /node_modules/,
                    use: [
                        {
                            loader: "ts-loader"
                        }
                    ]
                },
                {
                    enforce: "pre",
                    test: /\.js$/,
                    loader: "source-map-loader"
                },
                {
                    test: /\.s?css$/,
                    use: ['style-loader', 'css-loader', 'sass-loader']
                },
                {
                    test: /\.js$/,
                    exclude: /(node_modules|bower_components)/,
                    use: [
                      {
                        loader: "babel-loader",
                        options: {
                          cacheDirectory: ".cache/babel"
                        }
                      }
                    ]
                  },
                {
                    test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                    loader: "url-loader"
                },
                {
                    test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
                    loader: "file-loader"
                },
                {
                    test: /\.(jpg|jpeg|png|gif|pdf|ico|mp4|obj)$/,
                    loader: "file-loader"
                }
            ]
        },
        plugins: [
            new CleanWebpackPlugin(),
            new HtmlWebpackPlugin({
                template: './src/index.html',
                inject: "body",
                minify:{
                    minifyCSS: true,
                    minifyJS: true,
                    collapseWhitespace: true
                }
            })
        ]
    }
olivier dumas

I think you need to install @types/jest ts-jesthere with npm or yarn depending of your preference...

yarn add --save-dev @types/jest ts-jest

or

npm install --save-dev @types/jest ts-jest

You can find more infos here : https://olavihaapala.fi/2019/02/04/using-jest-with-typescript.html

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

SyntaxError: Unexpected reserved word on typescript

Jest test fail: SyntaxError: Unexpected token <

jest: Test suite failed to run, SyntaxError: Unexpected token import

SyntaxError: Unexpected reserved word on running mocha with enzyme

Node.js application SyntaxError: Unexpected reserved word 'class'

React JS Jest causing "SyntaxError: Unexpected token ."

Jest: "SyntaxError: Unexpected token {"

Unexpected use of reserved word 'import React-native

Jest test on typescript file syntax error: "interface is a reserved word in strict mode"

Jest - SyntaxError: Unexpected identifier

How to get rid of SyntaxError: Unexpected Token { when trying to test a React-Native with a Mapbox in Jest?

SyntaxError: Use of reserved word 'class' on implementing phantomjs in angular 8 application

SyntaxError: Unexpected identifier when running jest in TypeScript CRA project

for await gives SyntaxError: Unexpected reserved word inside a async function

SyntaxError: Unexpected reserved word, for await loop

SyntaxError: Unexpected reserved word => prettier/third-party.js

Unexpected reserved word error using Jest

TypeScript: Unexpected reserved word

Jint "unexpected reserved word"

SyntaxError: Invalid or unexpected token when testing react application with babel and jest

Unexpected reserved word 'await'

Typescript Interface SyntaxError: Unexpected identifier at interface name

Unexpected reserved word 'await' in async function in react

SyntaxError: unexpected reserved word 'await' in async function

React JS Unexpected reserved word 'await'

Unexpected reserved word 'await' for react native

Firestore: Uncaught SyntaxError: Unexpected reserved word

SyntaxError: Unexpected reserved word "await"

Uncaught SyntaxError: Unexpected reserved word in a {name} file