1

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
                }
            })
        ]
    }

2 Answers 2

2

You might need to install @babel/preset-typescript and then add it into your babel config or .babelrc presets array:

   presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I did install, I tried different configurations with that with no luck
The link reference in your answer was very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.