Ошибка: приложение (...): ничего не было возвращено из рендера. Обычно это означает, что отсутствует инструкция возврата. Или, чтобы ничего не визуализировать, верните null - PullRequest
0 голосов
/ 28 апреля 2020

У меня проблема с тестами на шутки и энзимы. В начале: это не дубликат, так как я не делал ошибок, описанных в похожих вопросах.

Мой App.tsx:

import React from 'react';

export class App extends React.Component<{}, {}> {
    render(): JSX.Element {
        return <div>abc</div>;
    }
}

Мой App.test.tsx:

import * as React from 'react';
import {mount, ReactWrapper} from 'enzyme';
import App from '../src/App';

describe('App', () => {
    it('renders', () => {
        const wrapper: ReactWrapper = mount(<App/>);

        expect(wrapper).toMatchSnapshot();
    })
})

Мой package.json:

{
  "name": "andretweb",
  "version": "0.1.0",
  "private": true,
  "author": "Alicja Kozik",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "@babel/core": "^7.9.0",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/plugin-proposal-object-rest-spread": "^7.9.5",
    "@babel/preset-env": "^7.9.5",
    "@babel/preset-react": "^7.9.4",
    "@babel/preset-typescript": "^7.9.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@types/enzyme": "^3.10.5",
    "@types/jest": "^25.2.1",
    "@types/node": "^13.13.4",
    "@types/react": "^16.9.34",
    "@types/react-dom": "^16.9.7",
    "babel-loader": "^8.1.0",
    "css-loader": "^3.5.3",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "enzyme-to-json": "^3.4.4",
    "file-loader": "^6.0.0",
    "html-webpack-plugin": "^4.2.1",
    "jest": "^25.4.0",
    "jest-css-modules": "^2.1.0",
    "jest-environment-enzyme": "^7.1.2",
    "jest-enzyme": "^7.1.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "sass": "^1.26.5",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "tslint": "^6.1.2",
    "tslint-immutable": "^6.0.1",
    "typescript": "^3.8.3",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "scripts": {
    "test": "jest --colors --coverage",
    "start": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production",
    "check-types": "tsc"
  },
  "jest": {
    "clearMocks": true,
    "collectCoverageFrom": [
      "**/*.tsx",
      "**/*.ts"
    ],
    "coverageDirectory": "coverage/jest",
    "moduleFileExtensions": [
      "js",
      "jsx",
      "node",
      "ts",
      "tsx"
    ],
    "collectCoverage": true,
    "coveragePathIgnorePatterns": [
      "\\\\node_modules\\\\",
      "<rootDir>/webapp/test/dataProviders/.*\\.ts"
    ],
    "coverageReporters": [
      "json",
      "text",
      "html"
    ],
    "setupFilesAfterEnv": [
      "jest-enzyme"
    ],
    "testEnvironment": "enzyme",
    "testEnvironmentOptions": {
      "enzymeAdapter": "react16"
    },
    "testPathIgnorePatterns": [
      "<rootDir>/webapp/test/dataProviders/.*\\.ts"
    ],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "setupFiles": [
      "./webapp/test/setup-tests.js"
    ],
    "roots": [
      "<rootDir>/webapp/test/"
    ],
    "moduleDirectories": [
      "<rootDir>",
      "node_modules",
      "webapp/src"
    ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/webapp/test/__mocks__/fileMock.ts",
      "\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/jest-css-modules"
    }
  }
}

Структура моего проекта:

<rootDir>
├───node_modules
└───webapp
    ├───resources
    │   └───images
    ├───src
    │   ├──typings
    │   └──App.tsx
    └───test
        ├───__mocks__
        ├───__snapshots__
        └───App.test.tsx

А если нужно, вот мой tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "outDir": "./dist/",
    "strictNullChecks": true,
    "moduleResolution": "node",
    "allowJs": true,
    "noEmit": true,
    "strict": true,
    "esModuleInterop": true,
    "jsx": "react",
    "baseUrl": "./webapp/src",
    "lib": [
      "es2015",
      "dom.iterable",
      "es2016.array.include",
      "es2017.object",
      "dom"
    ],
    "module": "es6",
    "removeComments": true,
    "alwaysStrict": true,
    "allowUnreachableCode": false,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "forceConsistentCasingInFileNames": true,
    "importHelpers": true
  }
}

Я просто запускаю команду npm test и получаю ошибку:

К вашему сведению: я также пытался преобразовать этот компонент класса в функцию один:

function App(): JSX.Element {
    return <div>abc</div>;
}

И ничего не изменилось.

Реактивное приложение администрируется веб-пакетом со следующим скриптом в webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    // webpack will take the files from ./src/index
    entry: './webapp/src/index',

    // and output it into /dist as bundle.js
    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'bundle.js'
    },

    // adding .ts and .tsx to resolve.extensions will help babel look for .ts and .tsx files to transpile
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },

    module: {
        rules: [
            // we use babel-loader to load our jsx and tsx files
            {
                test: /\.(ts|js)x?$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            },

            {
                test: /\.(sc|sa|c|le)ss$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                loader: 'file-loader',
                options: {
                    name: '[path][name].[ext]',
                    context: ''
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './webapp/index.html'
        })
    ]
};

Понятия не имею, что пошло не так.

1 Ответ

0 голосов
/ 30 апреля 2020

Я нашел решение. Несколько библиотек отсутствовали. Вот мои исправления package.json:

{
  "name": "andretweb",
  "version": "0.1.0",
  "private": true,
  "author": "Alicja Kozik",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "@babel/core": "^7.9.6",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/plugin-proposal-decorators": "^7.8.3",
    "@babel/plugin-proposal-optional-chaining": "^7.9.0",
    "@babel/plugin-transform-async-to-generator": "^7.8.3",
    "@babel/plugin-transform-regenerator": "^7.8.7",
    "@babel/plugin-transform-runtime": "^7.9.6",
    "@babel/preset-env": "^7.9.6",
    "@babel/preset-react": "^7.9.4",
    "@babel/preset-typescript": "^7.9.0",
    "@babel/runtime": "^7.9.6",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@types/enzyme": "^3.10.5",
    "@types/jest": "^25.2.1",
    "@types/node": "^13.13.4",
    "@types/react": "^16.9.34",
    "@types/react-dom": "^16.9.7",
    "babel-core": "^6.26.3",
    "babel-jest": "^25.5.1",
    "babel-loader": "^8.1.0",
    "css-loader": "^3.5.3",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "enzyme-to-json": "^3.4.4",
    "file-loader": "^6.0.0",
    "html-webpack-plugin": "^4.2.1",
    "jest": "^25.5.2",
    "jest-css-modules": "^2.1.0",
    "jest-environment-enzyme": "^7.1.2",
    "jest-enzyme": "^7.1.2",
    "mini-css-extract-plugin": "^0.9.0",
    "node-sass": "^4.14.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-test-renderer": "^16.13.1",
    "sass": "^1.26.5",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "ts-loader": "^7.0.2",
    "ts-jest": "^25.4.0",
    "tslint": "^6.1.2",
    "typescript": "^3.8.3",
    "url-loader": "^4.1.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "scripts": {
    "build:dev": "webpack --mode development",
    "build:prod": "webpack --mode production",
    "watch:dev": "webpack-dev-server --mode development --open --hot",
    "watch:prod": "webpack-dev-server --mode production --open --hot",
    "test": "jest --colors --coverage",
    "check-types": "tsc"
  },
  "jest": {
    "clearMocks": true,
    "collectCoverageFrom": [
      "**/*.tsx",
      "**/*.ts"
    ],
    "coverageDirectory": "coverage/jest",
    "moduleFileExtensions": [
      "js",
      "jsx",
      "node",
      "ts",
      "tsx"
    ],
    "collectCoverage": true,
    "coveragePathIgnorePatterns": [
      "\\\\node_modules\\\\",
      "<rootDir>/webapp/test/dataProviders/.*\\.ts"
    ],
    "coverageReporters": [
      "json",
      "text",
      "html"
    ],
    "setupFilesAfterEnv": [
      "jest-enzyme"
    ],
    "testEnvironment": "enzyme",
    "testEnvironmentOptions": {
      "enzymeAdapter": "react16"
    },
    "testPathIgnorePatterns": [
      "<rootDir>/webapp/test/dataProviders/.*\\.ts"
    ],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "setupFiles": [
      "./webapp/test/setup-tests.js"
    ],
    "roots": [
      "<rootDir>/webapp/test/"
    ],
    "moduleDirectories": [
      "<rootDir>",
      "node_modules",
      "webapp/src"
    ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/webapp/test/__mocks__/fileMock.ts",
      "\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/jest-css-modules"
    }
  }
}

Отсутствуют библиотеки: @babel/runtime, babel-core, babel-jest, ts-loader и ts-jest.

...