Jest тест приложения React с TypeScript SyntaxError ... Неожиданное зарезервированное слово «интерфейс» - PullRequest
0 голосов
/ 17 января 2020

У меня есть простое приложение реакции (не create-реагировать-приложение) с TypeScript. Он работает без проблем, но тесты завершаются с ошибкой «SyntaxError ... Неожиданное зарезервированное слово« interface »». Как заставить jest распознавать синтаксис интерфейса из TypeScript? Я сломал голову, пытаясь найти разные решения.

Компонент

    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;

Тест

   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();
    });
});

Шут Конфигурация в упаковке

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

1 Ответ

0 голосов
/ 17 января 2020

Я думаю, вам нужно установить @types/jest ts-jest здесь с npm или пряжей в зависимости от ваших предпочтений ...

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

или

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

Вы можете найти больше информации здесь: https://olavihaapala.fi/2019/02/04/using-jest-with-typescript.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...