Jest encountered an unexpected token - React with jest and enzyme - javascript

tsconfig.json
{
"extends": "./node_modules/pcf-scripts/tsconfig_base.json",
"compilerOptions": {
"typeRoots": ["node_modules/#types"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"sourceMap": true
},
"include": ["./ConsumptionSummaryComponent/src", "ConsumptionSummaryComponent/globals.d.ts"],
"exclude": ["./node_modules/pcf-scripts/./node_modules"]
}
.babelrc file
{
"env": {
"test": {
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
}
}
Package.json
{
"name": "pcf-project",
"version": "1.0.0",
"description": "Project containing your PowerApps Component Framework (PCF) control.",
"scripts": {
"build": "pcf-scripts build",
"clean": "pcf-scripts clean",
"rebuild": "pcf-scripts rebuild",
"start": "pcf-scripts start",
"test": "jest",
"test:watch": "jest --watch"
},
"jest": {
"roots": [
"<rootDir>/ConsumptionSummaryComponent/src"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
"^.+\\.tsx?$": "ts-jest",
"^.+\\.jsx$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"testEnvironment": "node",
"setupFiles": [
"<rootDir>/ConsumptionSummaryComponent/src/setupEnzyme.ts"
],
"globals": {
"ts-jest": {
"tsConfig": "tsconfig.json",
"babelConfig": "<rootDir>/ConsumptionSummaryComponent/.babelrc",
"diagnostics": {
"ignoreCodes": [
"TS1149"
]
}
}
},
"collectCoverage": true,
"coverageReporters": ["lcov"],
"coverageDirectory": "test-coverage",
"collectCoverageFrom": [
"<rootDir>/ConsumptionSummaryComponent/src/components/**/*.{ts,tsx}",
"<rootDir>/ConsumptionSummaryComponent/src/services/**/*.{ts,tsx}"
],
"coverageThreshold": {
"global": {
"branches": 0,
"functions": 0,
"lines": 0,
"statements": 0
}
},
"moduleNameMapper": {
"ts-jest": "<rootDir>/node_modules/ts-jest",
"office-ui-fabric-react/lib/": "office-ui-fabric-react/lib-commonjs/",
"#uifabric/fluent-theme/lib/": "#uifabric/fluent-theme/lib-commonjs/",
"#uifabric/styling/lib/": "#uifabric/styling/lib-commonjs/",
"expose-loader\\?jQuery\\!jquery": "<rootDir>/ConsumptionSummaryComponent/src/blank-mock",
"^style-loader.*$": "<rootDir>/ConsumptionSummaryComponent/src/blank-mock",
"^.*.svg$": "<rootDir>/src/blank-mock.js"
},
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
},
"dependencies": {
"#apollo/react-hooks": "^3.1.3",
"#common-pcf/sdk": "file:../sdk/common-pcf-sdk-1.0.0.tgz",
"#microsoft/applicationinsights-web": "^2.3.1",
"#types/node": "^10.12.18",
"#types/powerapps-component-framework": "^1.2.0",
"#uifabric/icons": "^7.3.2",
"apollo-boost": "^0.4.7",
"cra-template-typescript": "^1.0.0",
"enzyme": "^3.11.0",
"graphql": "^14.6.0",
"graphql-tag": "^2.10.2",
"office-ui-fabric-react": "^7.84.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
},
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#graphql-codegen/introspection": "1.12.1",
"#graphql-codegen/typescript": "1.12.1",
"#graphql-codegen/typescript-operations": "1.12.1",
"#graphql-codegen/typescript-react-apollo": "1.12.1",
"#types/enzyme": "3.10.5",
"#types/enzyme-adapter-react-16": "1.0.6",
"#types/jest": "^25.1.1",
"#types/react": "^16.9.19",
"#types/react-dom": "^16.9.5",
"babel-jest": "^25.1.0",
"enzyme-adapter-react-16": "^1.15.2",
"enzyme-to-json": "3.4.4",
"jest": "^25.1.0",
"pcf-scripts": "^1",
"pcf-start": "^1",
"source-map-loader": "^0.2.4",
"ts-jest": "25.1.0",
"ts-loader": "^6.2.1"
}
}
SetupEnzyme.ts
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
testcase
import * as React from "react";
import { shallow } from "enzyme";
import { DataModel } from "../../utils/DataModel";
import { styles } from "../../utils/style";
import { Enums } from "../../utils/enums";
import SummaryComponent from "../SummaryComponent";
const testProp: DataModel.ProductGroupSummaryViewModel = {
consumptionText: "300 Subscriptions . 200 Active . $500 ACR",
iconName: Enums.ProductTypeLogo.azureLogo,
iconStyle: styles.AzureIcon,
productGroupName: Enums.ProductTypeName.azureProductTypeName,
isEnabled:true,
order: 1
};
it("Should render the Summary component for the test Product Group Summary", () => {
const result = shallow(<SummaryComponent {...testProp} />);
expect(result).toMatchSnapshot();
});
Error
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
C:\DemandResponse\CSM-RCMND-DIGI-DigExp-UXWidgets\CSM-RCMND-DIGI-DigExp-UXWidgets\msp_RecommendationComponentSolution\ConsumptionSummaryComponent\ConsumptionSummaryComponent\src\setupEnzyme.ts:1
import { configure } from 'enzyme';
^^^^^^
SyntaxError: Cannot use import statement outside a module
It is working in other system but not in my system. Every thing is latest in my system.
Kindly help me with the issue

missing preset and no need for enzymeSetup to be ts file
would take the jest configuration to stand alone file to make life easier :)
jest.config.js
module.exports = {
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'<rootDir>/src/**/*.tsx',
],
moduleDirectories: ['node_modules', 'src'],
testPathIgnorePatterns: ['<rootDir>/test/setup/'],
setupFilesAfterEnv: ['<rootDir>/test/setup/setupEnzyme.js'],
transform: {
'\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: ['<rootDir>/node_modules/'],
testRegex: 'test/.*\\.test\\.tsx?$',
preset: 'ts-jest',
moduleFileExtensions: ['ts', 'tsx', 'js'],
moduleNameMapper: {
'\\.(png)$': '<rootDir>/test/setup/fileMock.js',
'\\.(css|less)$': '<rootDir>/test/setup/fileMock.js',
},
};
collect coverage only for ts and tsx files.
transform all js and jsx files via babel-jest
apply preset ts-jest for ts and tsx files
mock styles and images with plain empty js file.
setupEnzyme.js
require('#babel/polyfill');
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });

Related

How to parse esm module in vuejs

I'm encountering the following error in my vue project after packages update:
Failed to compile.
./node_modules/#polkadot/networks/packageInfo.js 6:27
Module parse failed: Unexpected token (6:27)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export const packageInfo = {
| name: '#polkadot/networks',
> path: new URL('.', import.meta.url).pathname,
| type: 'esm',
| version: '8.3.1'
Honestly I've tried lot of suggestions found across the internet and nothing appears to solve it.
My package.json:
{
"name": "polkadot-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#polkadot/extension-dapp": "0.42.2",
"#polkadot/keyring": "^8.1.2",
"core-js": "^3.6.5",
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^9.1.2",
"vue-router": "^3.2.0",
"vuetify": "^2.4.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.18.0",
"#typescript-eslint/parser": "^4.18.0",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-router": "^4.5.15",
"#vue/cli-plugin-typescript": "~4.5.0",
"#vue/cli-plugin-vuex": "^4.5.15",
"#vue/cli-service": "~4.5.0",
"#vue/eslint-config-standard": "^5.1.2",
"#vue/eslint-config-typescript": "^7.0.0",
"eslint": "^6.7.2",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.0",
"eslint-plugin-vue": "^6.2.2",
"sass": "~1.32.0",
"sass-loader": "^10.0.0",
"typescript": "~4.1.5",
"vue-cli-plugin-vuetify": "~2.4.5",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.7.0"
}
}
My tsconfig:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"#/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
My vue.config.js
module.exports = {
transpileDependencies: [
'vuetify'
]
}
My babel.config.js
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
Does anyone have idea how to fix this? As far as I understand from the error my webpack can't parse the js file from the module. But aren't the js files supported by default in webpack?
My understanding is that somehow I need to specify in vue.config.js that I'm using esm modules, and how they can be loaded and parsed.
Any ideas will be greatly appreciated!
It appears that this is known issue with webpack 4 and older versions (I think it is fixed in version 5).
Basically in order webpack to be able to parse the problematic files it needs additional package:
https://www.npmjs.com/package/#open-wc/webpack-import-meta-loader
Once I've installed the package I've included it in my vue webpack config via the vue.config.js file as follows:
const {VueLoaderPlugin} = require("vue-loader");
module.exports = {
transpileDependencies: [
'vuetify'
],
configureWebpack: {
module: {
rules: [
{
test: /\.js$/,
loader: require.resolve('#open-wc/webpack-import-meta-loader'),
}
]
}
}
}
In my case solution proposed by #themartto was not working.
I had to set vue.config.js
{
transpileDependencies: [
'affected-dependency'
],
chainWebpack (config)
{
config.module
.rule('js')
.test(/\.js$/)
.use('#open-wc/webpack-import-meta-loader')
.loader('#open-wc/webpack-import-meta-loader');
}
}

Testing Angular application using Jest - Jest encountered an unexpected token

I am using Jest for testing my Angular application but am getting the following errors:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/home/cxo/Projects/git/sparta/clients/vaph/node_modules/#ckeditor/ckeditor5-watchdog/src/editorwatchdog.js:12
import { throttle, cloneDeepWith, isElement } from 'lodash-es';
^
SyntaxError: Unexpected token {
at Runtime.createScriptFromCode (../../../node_modules/jest-runtime/build/index.js:1258:14)
at ../../../node_modules/#ckeditor/ckeditor5-angular/bundles/ckeditor-ckeditor5-angular.umd.js:2:85
at Object.<anonymous> (../../../node_modules/#ckeditor/ckeditor5-angular/bundles/ckeditor-ckeditor5-angular.umd.js:5:2)
Am also using https://nx.dev/angular.
This is my jest config:
module.exports = {
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
transform: {
'^.+\\.(ts|js|html)$': 'ts-jest',
},
resolver: '#nrwl/jest/plugins/resolver',
moduleFileExtensions: ['ts', 'js', 'html'],
coverageReporters: ['html'],
};
My package.json looks like:
{
"name": "App-Name",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"nx": "nx",
"start": "ng serve",
// SEVERAL ENTRIES ARE OMITTED FOR CLARITY
},
"private": true,
"dependencies": {
"#angular/animations": "^9.1.12",
"#angular/cdk": "~9.2.4",
"#angular/common": "^9.1.12",
"#angular/compiler": "^9.1.12",
"#angular/core": "^9.1.12",
"#angular/forms": "^9.1.12",
"#angular/localize": "~9.1.12",
"#angular/material": "~9.2.4",
"#angular/material-moment-adapter": "^9.2.4",
"#angular/platform-browser": "^9.1.12",
"#angular/platform-browser-dynamic": "^9.1.12",
"#angular/router": "^9.1.12",
"#angular/service-worker": "~9.1.12",
"#auth0/angular-jwt": "^4.1.2",
"#babel/polyfill": "^7.10.4",
"#ckeditor/ckeditor5-angular": "^1.2.3",
"#ckeditor/ckeditor5-build-balloon": "^19.0.0",
"#ckeditor/ckeditor5-build-balloon-block": "^19.0.0",
"#ckeditor/ckeditor5-build-classic": "^19.0.0",
"#ckeditor/ckeditor5-build-decoupled-document": "^19.0.0",
"#ckeditor/ckeditor5-build-inline": "^19.0.0",
"#nrwl/angular": "9.5.1",
"angular-build-info": "^1.0.7",
"angular-notifier": "^6.0.1",
"core-js": "^2.5.4",
"file-saver": "^2.0.2",
"ng2-file-upload": "^1.4.0",
// SEVERAL ENTRIES ARE OMITTED FOR CLARITY
"secure-ls": "^1.2.6",
"zone.js": "^0.10.2"
},
"devDependencies": {
"#angular-devkit/build-angular": "^0.901.11",
"#angular/cli": "^9.1.11",
"#angular/compiler-cli": "^9.1.12",
"#angular/language-service": "^9.1.12",
"#compodoc/compodoc": "^1.1.11",
"#ngneat/spectator": "^5.12.0",
"#nrwl/cypress": "9.5.1",
"#nrwl/jest": "9.5.1",
"#nrwl/workspace": "9.5.1",
"#types/crypto-js": "^3.1.47",
"#types/jest": "25.1.4",
"#types/node": "~12.12.50",
"dotenv": "6.2.0",
"eslint": "6.8.0",
"jest": "25.2.3",
"jest-preset-angular": "8.1.2",
"ng-mocks": "^10.1.1",
"ng-openapi-gen": "^0.12.1",
"ts-jest": "25.2.1",
"ts-node": "~7.0.0",
"tslint": "~6.0.0",
"typescript": "~3.8.3"
}
}
tsconfig.json looks like:
{
"compileOnSave": false,
"compilerOptions": {
"rootDir": ".",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es2015",
"module": "esnext",
"typeRoots": ["node_modules/#types"],
"lib": ["es2017", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {
// SEVERAL LINES OMITTED FOR CLARITY
}
},
"exclude": ["node_modules", "tmp"]
"compilerOptions": {
"types": ["node", "jest"]
},
"include": ["**/*.ts"]
}
This is the tsconfig.lib.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"target": "es2015",
"declaration": true,
"inlineSources": true,
"types": [],
"lib": ["dom", "es2018"]
},
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"enableResourceInlining": true
},
"exclude": ["src/test-setup.ts", "**/*.spec.ts"]
}
This is tsconfig.spec.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
I have searched the web and debugged, but to no avail. I did what was suggested in this post but to no avail.
In the error message it says that By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
I don't know if I have to install babeljs also.
Since some vendors publish their sources without transpiling, so you need to transpile these packages again with babel-jest while ts-jest will take care ts files. In addition, you should transform these packages again by specifying transformIgnorePatterns. Here is your changed Jest config:
const esModules = ['#ckeditor', 'lodash-es'].join('|'); // you can put more if there is others
module.exports = {
transform: {
'^.+\\.(ts|html)$': 'ts-jest',
'^.+\\.js$': 'babel-jest',
},
// ...
transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
};
Just keep in mind, install babel, babel-jest & its preset and create the config for it:
// Install
npm i -D #babel/core #babel/preset-env babel-jest
// babel.config.js
module.exports = function(api) {
api.cache(true);
const presets = ['#babel/preset-env'];
const plugins = [];
return {
presets,
plugins,
};
};
I ran into the same issue when switching from lodash to lodash-es. I did what #tmhao2005 suggested and installed #babel/core, #babel/preset-env and babel-jest then added a babel.config.js in the root of my Nx Worspace and updated the base jest.config.ts. so you can try the following.
Install dependencies
yarn add -D #babel/core #babel/preset-env babel-jest
npm I -D #babel/core #babel/preset-env babel-jest
Add babel.config.js
In the root of your Nx Workspace add a babel.config.js with the following taken from the Jest docs
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current'
}
}
]
]
};
Update jest.config.ts
Update the base jest.config.ts in the root of your Nx Workspace to something like this depending on your configuration needs.
module.exports = {
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
transform: {
'^.+\\.(ts|html)$': 'ts-jest',
'^.+\\.js$': 'babel-jest'
},
resolver: '#nrwl/jest/plugins/resolver',
moduleFileExtensions: ['ts', 'js', 'html'],
coverageReporters: ['html', 'json'],
transformIgnorePatterns: ['/node_modules/(?!lodash-es)']
};
This approach worked for me using NX 10 for lodash-es but your mileage may vary with the #ckeditor packages. You will have to add all #ckeditor packages you want to the transformIgnorePatterns
Some possible helpful links
NX issue 1091
NX issue 812

Why does my vue web app load a blank page in IE11 and look broken in Edge?

I'm having a bit of trouble with getting my project to work on IE11 and Edge
You can view it here: https://tagfireandsecurity.co.uk/
THE PROBLEMS
IE11: Blank page, shows multiple errors:
SCRIPT1002: Syntax error
firebase-app.js (1,1)
SCRIPT1002: Syntax error
firebase-analytics.js (1,1)
SCRIPT1002: Syntax error
init.js (1,1)
SCRIPT5043: Accessing the 'caller' property of a function or arguments object is not allowed in strict mode
eval code (3959) (15268,9)
SCRIPT5022: SecurityError
sockjs.js (1684,3)
Edge: Loads the website, however its all messed up. For example the grid is not working and my carousels aren't working. Also shows some errors:
SCRIPT65535: SCRIPT65535: Invalid calling object
WHAT I'VE DONE SO FAR
I tried to make sure babel will polyfill which I don't even know if it's doing it to be honest, I followed the documentation on their website and I don't think its working.
I also tried to add transpileDependencies: ['vue-mq', 'vue-carousel', 'firebase', 'vue-lazyload-video'] to polyfill my plugins but I don't think that is doing anything either.
I also added an autoprefixer and I believe that is working because the SCSS to CSS output now has all the prefixes in it, so why it's not working in EDGE? I don't know. Inspecting it in Edge shows it has the prefixes there, sometimes just disabling the prefix and putting it back on again fixes it so I'm very confused.
Here are my config files:
babel.config.js
module.exports = {
presets: [
['#vue/app', {
polyfills: [
'es.promise',
'es.symbol'
]
}]
]
};
webpack.config.js
module.exports = {
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
}],
vue: {
// configure autoprefixer
autoprefixer: {
browsers: ['last 2 versions']
}
}
}
}
vue.config.js
// vue.config.js
module.exports = {
transpileDependencies: ['vue-mq', 'vue-carousel', 'firebase', 'vue-lazyload-video']
}
main.ts
import "core-js/stable";
import "regenerator-runtime/runtime";
require('intersection-observer');
import "regenerator-runtime/runtime";
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "#fortawesome/fontawesome-free/css/all.css";
import VueMq from "vue-mq";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import VueCarousel from "vue-carousel";
import "animate.css/animate.css";
import * as firebase from "firebase";
import VueLazyLoadVideo from "vue-lazyload-video";
require("intersection-observer");
require("matchmedia-polyfill");
require("matchmedia-polyfill/matchMedia.addListener");
import "lazysizes";
import "lazysizes/plugins/parent-fit/ls.parent-fit";
import "lazysizes/plugins/blur-up/ls.blur-up";
// Register Components
// LazyVideo & LazyVideoAsGIF
Vue.use(VueLazyLoadVideo);
const firebaseConfig = {
HIDDEN CONFIG FOR STACKOVERFLOW
};
firebase.initializeApp(firebaseConfig);
Vue.use(VueCarousel);
gsap.registerPlugin(ScrollTrigger);
Vue.use(VueMq, {
breakpoints: {
// default breakpoints - customize this
sm: 480,
md: 921,
lg: 1024
}
});
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
postcss.config.js
module.exports = {
plugins: [
require('autoprefixer')({})
]
};
package.json
{
"name": "tag",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#firebase/polyfill": "^0.3.36",
"#fortawesome/fontawesome-free": "^5.13.0",
"animate.css": "^4.1.0",
"axios": "^0.19.2",
"core-js": "^3.6.5",
"firebase": "^7.15.5",
"gsap": "^3.4.0",
"intersection-observer": "^0.11.0",
"lazysizes": "^5.2.2",
"matchmedia-polyfill": "^0.3.2",
"uuid": "^8.2.0",
"vue": "^2.6.11",
"vue-carousel": "^0.18.0",
"vue-class-component": "^7.2.3",
"vue-lazyload-video": "^0.1.15",
"vue-mq": "^1.0.1",
"vue-property-decorator": "^8.4.2",
"vue-router": "^3.2.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"#babel/preset-env": "^7.10.4",
"#typescript-eslint/eslint-plugin": "^2.33.0",
"#typescript-eslint/parser": "^2.33.0",
"#vue/cli-plugin-babel": "^4.4.6",
"#vue/cli-plugin-eslint": "~4.4.0",
"#vue/cli-plugin-router": "~4.4.0",
"#vue/cli-plugin-typescript": "~4.4.0",
"#vue/cli-plugin-vuex": "~4.4.0",
"#vue/cli-service": "~4.4.0",
"#vue/eslint-config-prettier": "^6.0.0",
"#vue/eslint-config-typescript": "^5.0.2",
"autoprefixer": "^9.8.5",
"cssnano": "^4.1.10",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-vue": "^6.2.2",
"fork-ts-checker-webpack-plugin": "^5.0.5",
"google-auth-library": "^6.0.5",
"node-sass": "^4.12.0",
"postcss-import": "^12.0.1",
"postcss-load-config": "^2.1.0",
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
"prettier": "^1.19.1",
"sass-loader": "^8.0.2",
"sugarss": "^2.0.0",
"typescript": "~3.9.3",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended",
"#vue/typescript/recommended",
"#vue/prettier",
"#vue/prettier/#typescript-eslint"
],
"parserOptions": {
"ecmaVersion": 2020
},
"rules": {}
},
"browserslist": [
"last 1 version",
"> 1%",
"IE 10"
]
}
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"jsx": "preserve",
"allowJs": true,
"strict": false,
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"#/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
Sorry to say this, you can't render a website built with JS based framework (VUE, ReactJS etc) in IE, and the JS engine of Edge (non-chromium) is not capable of handling all features of ES6 standard. If the customer wants to use your website on a Microsoft based browser, then they have to switch to the latest Edge based on Chromium.

Minified React error #321 - React Typescript library build

I am writing my own React library with Typescript. I have a lot of problems with building and using it. I am using webpack with ts loader to build files into lib folder. When I am trying to use my components from build
import React from 'react'
import { Text } from '../lib'
export default () => {
return <Text lg>Blabla</Text>
}
I get an error
index.js:9 Uncaught Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
What is wrong?
tsconfig
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "esnext"],
"allowJs": true,
"outDir": "./lib/",
"noImplicitAny": true,
"allowSyntheticDefaultImports": true,
"module": "esnext",
"jsx": "react",
"moduleResolution": "node",
"esModuleInterop": true,
"declaration": true,
"typeRoots": ["node_modules/#types"]
},
"include": ["src"],
"exclude": ["node_modules"]
}
webpack
const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: path.resolve(__dirname, '../src/index.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve(__dirname, '../lib'),
library: 'my-library',
libraryTarget: 'umd',
umdNamedDefine: true
},
plugins: [new CleanWebpackPlugin()]
}
package.json
{
"name": "my-library",
"version": "1.0.0",
"private": true,
"types": "lib",
"main": "lib/index.js",
"dependencies": {
"#types/node": "^14.0.11",
"#types/react": "^16.9.35",
"#types/react-dom": "^16.9.8",
"#types/styled-components": "^5.1.0",
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^4.3.0",
"prettier": "^2.0.5",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"styled-components": "^5.1.1",
"ts-loader": "^7.0.5",
"typescript": "^3.9.5",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"scripts": {
"build": "webpack --config config/webpack.prod.js",
"dev": "webpack-dev-server --mode development --open --hot --config config/webpack.dev.js",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook"
},
"devDependencies": {
"#babel/core": "^7.10.2",
"#storybook/addon-actions": "^5.3.19",
"#storybook/addon-links": "^5.3.19",
"#storybook/addons": "^5.3.19",
"#storybook/react": "^5.3.19",
"babel-loader": "^8.1.0"
}
}

[React-Native][Jest]SyntaxError: Unexpected token import

It seems babel transform works in my testcase code, but es6 syntax in node_modules does not.
Error
environment
npm 4.5
MacOS Sierra
jest config
{
"preset": "react-native",
"globals": {
"__DEV__": true
},
"transform": {
"^.+\\.js$": "babel-jest"
}
}
babelrc
{
"env": {
"test": {
"presets": ["react-native"],
"plugins": [["import", { "libraryName": "antd-mobile" }]]
},
"development": {
"presets": ["react-native"],
"plugins": [["import", { "libraryName": "antd-mobile" }]]
},
"production": {
}
}
}
testcase
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import Index from '../index.ios.js';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
package.json
{
"private": true,
"scripts": {
"web": "roadhog server",
"build-web": "cross-env NODE_ENV=production roadhog build",
"start": "react-native start",
"ios": "cross-env NODE_ENV=development node themes/theme.rn.config.js && react-native run-ios",
"android": "cross-env NODE_ENV=development node theme/theme.rn.config.js && react-native run-android",
"lint": "eslint --ext .js src test",
"precommit": "npm run lint",
"test": "cross-env NODE_ENV=test jest --config .jest.config.json --no-cache"
},
"engines": {
"install-node": "6.9.2"
},
"theme": "./themes/theme.web.config.js",
"dependencies": {
"antd-mobile": "^1.0.8",
"babel-runtime": "^6.9.2",
"dva": "^1.2.1",
"lodash": "^4.17.4",
"moment": "^2.18.1",
"rc-form": "^1.3.0",
"react": "15.4.2",
"react-dom": "15.4.2",
"react-native": "0.42.3",
"react-native-chart": "^1.0.8-beta",
"react-native-gesture-password": "^0.2.0",
"react-native-scrollable-tab-view": "^0.7.4",
"react-native-smart-gesture-password": "^2.1.0",
"react-navigation": "^1.0.0-beta.7",
"recharts": "^0.21.2",
"socket.io-client": "^1.7.3"
},
"devDependencies": {
"babel-eslint": "^7.1.1",
"babel-jest": "^19.0.0",
"babel-plugin-dva-hmr": "^0.3.2",
"babel-plugin-import": "^1.1.1",
"babel-plugin-transform-runtime": "^6.9.0",
"babel-preset-react-native": "^1.9.1",
"cross-env": "^4.0.0",
"eslint": "^3.12.2",
"eslint-config-airbnb": "^13.0.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-jsx-a11y": "^2.2.3",
"eslint-plugin-react": "^6.8.0",
"expect": "^1.20.2",
"husky": "^0.13.3",
"jest": "^19.0.2",
"less-vars-to-js": "^1.1.2",
"postcss-pxtorem": "^4.0.0",
"react-test-renderer": "15.4.2",
"redbox-react": "^1.3.2",
"roadhog": "^0.6.0-beta1"
}
}
debug message
jest version = 19.0.2
test framework = jasmine2
config = {
"automock": false,
"bail": false,
"browser": false,
"cacheDirectory": "/var/folders/h3/bfmnzb_j3zg3pdffgps1w3vh0000gn/T/jest",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"expand": false,
"globals": {
"__DEV__": true
},
"haste": {
"defaultPlatform": "ios",
"platforms": [
"android",
"ios",
"native"
],
"providesModuleNodeModules": [
"react-native"
]
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"json",
"jsx",
"node"
],
"moduleNameMapper": [
[
"^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|png|psd|svg|webp)$",
"RelativeImageStub"
],
[
"^React$",
"/Users/erickim/Documents/Develop/react/glfm/node_modules/react"
]
],
"modulePathIgnorePatterns": [
"/Users/erickim/Documents/Develop/react/glfm/node_modules/react-native/Libraries/react-native/",
"/Users/erickim/Documents/Develop/react/glfm/node_modules/react-native/packager/"
],
"noStackTrace": false,
"notify": false,
"preset": "react-native",
"resetMocks": false,
"resetModules": false,
"roots": [
"/Users/erickim/Documents/Develop/react/glfm"
],
"snapshotSerializers": [],
"testEnvironment": "/Users/erickim/Documents/Develop/react/glfm/node_modules/jest-environment-node/build/index.js",
"testMatch": [
"**/__tests__/**/*.js?(x)",
"**/?(*.)(spec|test).js?(x)"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": "",
"testResultsProcessor": null,
"testURL": "about:blank",
"timers": "real",
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-clone-referenced-element)"
],
"useStderr": false,
"verbose": null,
"watch": false,
"setupFiles": [
"/Users/erickim/Documents/Develop/react/glfm/node_modules/babel-polyfill/lib/index.js",
"/Users/erickim/Documents/Develop/react/glfm/node_modules/react-native/jest/setup.js"
],
"transform": [
[
"^.+\\.js$",
"/Users/erickim/Documents/Develop/react/glfm/node_modules/babel-jest/build/index.js"
]
],
"rootDir": "/Users/erickim/Documents/Develop/react/glfm",
"name": "005c8bf9b4d78dfa0bb0e32c0c55b0fb",
"testRunner": "/Users/erickim/Documents/Develop/react/glfm/node_modules/jest-jasmine2/build/index.js",
"cache": false,
"watchman": true
}
I figured it out. By default jest doesn't transform ES6 js code from node_modules. In my case, the package react-navigation module need to be translated. So I added transformIgnorePatterns to my jest configuration and everything worked:
{
"preset": "react-native",
"setupFiles": ["./test/setup.js"],
"globals": {
"__DEV__": true
},
"transform": {
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!react-native|react-navigation)/"
]
}
https://facebook.github.io/jest/docs/tutorial-react-native.html#transformignorepatterns-customization
The problem is that node doesn't understand ES6 modules and JEST is node process, so using import inside your test throw this error. Instead of babel we specifically tell Webpack to transcompile ES6 modules.So, we can fix this error by telling babel that when we are in testing scenario please combile ES6 modules by using below babel configuration settings
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
you can download this babel plugin by npm
npm install --save-dev babel-plugin-transform-es2015-modules-commonjs
Hopefully this will fix your problem.

Categories

Resources