#reactjs #typescript #jestjs #mocha.js #ts-jest
#reactjs #typescript #jestjs #mocha.js #ts-jest
Вопрос:
В настоящее время я пытаюсь выполнить модульное тестирование некоторых компонентов react, но при импорте модулей react возникают проблемы.
Ошибка, с которой я сталкиваюсь, заключается в следующем
C:UsersAndrew.UrrysourceWorkspacesEmpowerPlatformAdminPortalnode_modulesmpx-error-boundaryErrorBoundary.js:2
import * as React from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module
6 | import { PageHeader } from './SubMenu';
7 | import { msg } from 'mpx-multi-language';
> 8 | import { ErrorBoundary } from 'mpx-error-boundary';
jest.config.js файл следующий:
module.exports = {
"roots": [
"<rootDir>/wwwroot/ts-tests"
],
"testMatch": [
"**/__tests__/**/*. (ts|tsx|js)",
"**/?(*.) (spec|test). (ts|tsx|js)"
],
"transform": {
"^. \.(ts|tsx)$": "ts-jest"
},
}
файл package.json следующий:
{
"name": "app",
"version": "1.0.0",
"private": true,
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.9.0",
"@babel/node": "^7.8.7",
"@babel/preset-env": "^7.9.0",
"@babel/preset-react": "^7.10.1",
"@babel/preset-typescript": "^7.9.0",
"@babel/plugin-proposal-class-properties": "^7.10.4",
"@babel/plugin-transform-modules-commonjs": "^7.10.4",
"@babel/register": "^7.9.0",
"@types/bootstrap": "4.3.2",
"@types/chai": "^4.2.0",
"@types/enzyme-adapter-react-16": "^1.0.6",
"@types/jquery": "^3.5.0",
"@types/mocha": "^7.0.2",
"@types/react": "^16.9.31",
"@types/react-dom": "^16.9.6",
"@types/sinon": "^9.0.4",
"@types/jest": "26.0.10",
"babel-loader": "^8.1.0",
"chai": "^4.2.0",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.6.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"esm": "3.2.25",
"file-loader": "^6.0.0",
"hard-source-webpack-plugin": "^0.13.1",
"html-webpack-plugin": "^4.3.0",
"image-webpack-loader": "^6.0.0",
"jsdom": "^16.3.0",
"mini-css-extract-plugin": "^0.9.0",
"mocha": "^8.1.1",
"node-sass": "^4.14.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"sinon": "^9.0.2",
"sinon-chai": "3.5.0",
"terser-webpack-plugin": "^3.0.6",
"ts-loader": "^7.0.5",
"ts-mockito": "^2.5.0",
"ts-jest": "26.2.0",
"typescript": "3.8.3",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"ignore-styles": "^5.0.1",
"ts-node-register": "1.0.0",
"jest": "26.4.0"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^5.13.1",
"@material-ui/core": "^4.11.0",
"bootstrap": "^4.3.1",
"bootstrap-table": "^1.16.0",
"file-saver": "^2.0.2",
"jquery": "^3.3.1",
"jquery-validation": "^1.17.0",
"jquery-validation-unobtrusive": "^3.2.11",
"material-table": "^1.68.0",
"moment": "^2.26.0",
"mpx-dialog": "^1.1.12",
"mpx-error-boundary": "^1.0.0",
"mpx-multi-language": "^1.0.8",
"mpx-react-page-components": "^1.0.6",
"mpx-utilities": "^1.0.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"tableexport.jquery.plugin": "^1.10.20"
},
"babel": {
"presets": [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-modules-commonjs"
],
"transformIgnorePatterns": [
"node_modules/mpx-error-boundary/"
]
},
"jest": {
"moduleNameMapper": {
"\.(css|less)$": "identity-obj-proxy"
},
"transform": {
"\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
}
},
"mocha": {
"extension": [
"ts",
"tsx"
],
"spec": "wwwroot/ts-tests/**/*.test.tsx",
"require": [
"wwwroot/ts-tests/babel-register.js",
"ignore-styles"
]
},
"scripts": {
"test": "jest",
"pack-dev": "webpack --mode development --progress",
"pack-dev-profile": "webpack --mode development --verbose --profile --progress",
"pack-prod": "webpack --mode production",
"pack-library": "webpack --mode production --config webpack.library.config.js",
"clean": "del /Q /F .\wwwroot\dist\*.*"
}
}
babel-register.js файл следующий:
/* Copyright (©) Metapraxis Ltd, 2020 - 2020, all rights reserved */
// This cannot be done on the command line or in package.json due to this issue:
// https://github.com/babel/babel/issues/8962
const register = require('@babel/register').default;
register({
extensions: ['.ts', '.tsx', '.js', '.jsx']
});
tsconfig.json является следующим:
{
"compileOnSave": false,
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"allowUmdGlobalAccess": true,
"target": "ES6",
"module": "ES6",
"moduleResolution": "Node",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
"exclude": [
"node_modules"
],
"include": [
"./../Abstractions/*.d.ts",
"./../Abstractions/**/*.d.ts",
"./Models/*.d.ts",
"./wwwroot/ts/*",
"./wwwroot/ts-tests/**/*.test.ts",
"./wwwroot/ts-tests/**/*.test.tsx"
]
}
Я полагаю, что это проблема с несоответствием стилей импорта, но я не смог устранить проблему. Package.json включает в себя mocha, но в настоящее время для тестирования используется jest. И в mocha, и в jest возникает одна и та же проблема, поэтому она должна быть независимой от платформы тестирования.
Любая помощь по этому вопросу была бы высоко оценена
РЕДАКТИРОВАТЬ # 1: Импорт, на который он жалуется, присутствует во внешнем пакете NPM
РЕДАКТИРОВАТЬ # 2: Я полагаю, что проблема связана с тем, что babel не переносит модуль ES6 в ES5 для тестирования
Ответ №1:
Проблема может быть связана с тем, transformIgnorePatterns
что указано в package.json
. Попробуйте следующий трюк и посмотрите, решит ли он вашу проблему.
"transformIgnorePatterns": [
"node_modules/(?!(react|mpx-error-boundary)/)"
]
Комментарии:
1. Это в пакете NPM, но пакет, который я могу изменить. Я думаю, я мог бы просто изменить пакет NPM и заставить этот вызов импортировать React из «react»?
2. К сожалению, это не сработало. Я все еще получаю ту же ошибку из файла JavaScript, относящегося к импорту.
3. Пробовал и это, и это тоже не сработало. Хммм… Я продолжу изучать функциональность импорта модуля.