Testing Angular application using Jest - Jest encountered an unexpected token - javascript

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

Related

Vue JS server not compiling after changes to src files

I am new to Vue.js and I am having an issue and have been stuck for a long while trying different fixes.
After starting a dev server using npm run serve, I would expect that when I make changes to any .vue or .js files within my directory, the server would refresh and display these changes. However, no matter what I try nothing happens. Nothing is compiling and nothing changes within my terminal. The only way I can refresh the server is by closing it and running a new one. Refreshing my browser page does nothing either. Really stumped on this one so will be eternally grateful if anyone can help as none of the fixes I found on here have worked for me :(
My vue.config.js is as follows:
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
client: {
progress: true
},
hot: false,
watchFiles: {
paths: ['src/**/*.js', 'src/**/*.vue', 'src/**/*.json', 'src/views/*.vue']
},
liveReload: true,
}
})
My package.json is:
{
"name": "product-and-cart",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.8.3",
"nodemon": "^2.0.19",
"vue": "^3.2.13",
"vue-router": "^4.0.3"
},
"devDependencies": {
"#babel/core": "^7.12.16",
"#babel/eslint-parser": "^7.12.16",
"#vue/cli-plugin-babel": "~5.0.0",
"#vue/cli-plugin-eslint": "~5.0.0",
"#vue/cli-plugin-router": "~5.0.0",
"#vue/cli-service": "~5.0.0",
"#vue/eslint-config-standard": "^6.1.0",
"eslint": "^7.32.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-vue": "^8.0.3",
"sass": "^1.54.5",
"sass-loader": "^13.0.2",
"webpack": "^5.74.0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"#vue/standard"
],
"parserOptions": {
"parser": "#babel/eslint-parser"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead",
"not ie 11"
]
}
And my jsconfig.json is:
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"baseUrl": "./",
"moduleResolution": "node",
"paths": {
"#/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
],
"jsx": "preserve"
}
}
And babel.config.js:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
In your vue.config.js file, you set hot module replacement to false in devServer configuration; therefore, your changes won't be applied without refreshing the page. Hot module replacement is enabled by default in Vue CLI, you can remove hot from the configuration. Also, you don't have to set liveReload and watch options for this.
For more details, you can take a look at Vue CLI configuration and Webpack DevServer configuration.

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

"Failed to Compile" "Parsing error: Unexpected token :" during attempt to migrate to typescript in existing create-react-app

I have an existing create-react-app that I'm trying to migrate from javascript to typescript. I followed the migration guide on create-react-app.dev and installed the following:
npm install --save typescript #types/node #types/react #types/react-dom #types/jest
I then copied and pasted the code from Material-UI's example on this codesandbox example, into ResponsiveDrawer.tsx. When I start my server I get:
Failed to compile.
./src/components/ResponsiveDrawer.tsx
src/components/ResponsiveDrawer.tsx
Line 21:36: Parsing error: Unexpected token :
The line identified is:
const useStyles = makeStyles((theme: Theme) =>
I've played with my eslint config and downloaded various plugins. My package.json contains:
"#babel/preset-typescript": "^7.9.0",
"#types/react-router-dom": "^5.1.7",
"#typescript-eslint/eslint-plugin": "^4.24.0",
"#typescript-eslint/parser": "^4.24.0",
"eslint": "^7.27.0",
"eslint-plugin-import": "^2.23.3",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-react": "^7.23.2",
"typescript": "^3.9.9"
I initially had linting errors highlighted in the .tsx file, but that seems to have been resolved by adding the above. I'm still having problem compiling the app though. Does anyone know how to resolve?
I'm not sure what it was I did exactly, but I got it working. I watched a few youtube vids and tutorials. I'd recommend this one if anyone else is similarly stuck.
I made changes to the following:
package.json
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript"
],
"plugins": [
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-optional-chaining"
]
},
"devDependencies": {
"#babel/preset-typescript": "^7.9.0",
"#types/material-ui": "^0.21.8",
"#types/react-router-dom": "^5.1.7",
"#typescript-eslint/eslint-plugin": "^4.24.0",
"#typescript-eslint/parser": "^4.24.0",
"eslint": "^7.27.0",
"eslint-plugin-import": "^2.23.3",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-react": "^7.23.2",
"typescript": "^3.9.9"
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"jsx": "react",
"strict": true,
"noImplicitAny": false,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
.eslintrc.json
{
"root":true,
"parser": "#typescript-eslint/parser",
"plugins": ["react", "#typescript-eslint", "eslint-plugin-node"],
"files": ["**/*.ts", "**/*.tsx"],
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": ["plugin:react/recommended", "plugin:#typescript-eslint/recommended"],
...
}

Jest encountered an unexpected token - React with jest and enzyme

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

Jest test fails with Unexpected token, expected ";"

I have a Node project using Typescript and Jest. Currently I have this project structure
With this tsconfig.json file
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"allowJs": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true
}
this jest.config.js file
module.exports = {
clearMocks: true,
coverageDirectory: "coverage",
testEnvironment: "node",
};
and this package.json file
{
"scripts": {
"start": "node dist/App.js",
"dev": "nodemon src/App.ts",
"build": "tsc -p .",
"test": "jest"
},
"dependencies": {
"commander": "^3.0.1"
},
"devDependencies": {
"#types/jest": "^24.0.18",
"#types/node": "^12.7.4",
"jest": "^24.9.0",
"nodemon": "^1.19.2",
"ts-jest": "^24.0.2",
"ts-node": "^8.3.0",
"typescript": "^3.6.2"
}
}
I created a test file in my tests directory
import { App } from '../src/App';
describe('Generating App', () => {
let app: App;
test('It runs a test', () => {
expect(true).toBe(true);
});
});
but unfortunately I get a syntax error
SyntaxError: C:...\tests\App.test.ts: Unexpected token, expected ";"
(5:9)
at my app variable. It seems the test runner is not able to understand Typescript code. How can I fix my configuration to support Typescript in test files for Jest?
Try to add typescript extension in jest config :
module.exports = {
roots: ['<rootDir>'],
transform: {
'^.+\\.ts?$': 'ts-jest'
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
moduleFileExtensions: ['ts', 'js', 'json', 'node'],
collectCoverage: true,
clearMocks: true,
coverageDirectory: "coverage",
};
And then load the jest config in your package.json test script :
"scripts": {
"test": "jest --config ./jest.config.js",
...
},
tsconfig.json
"compilerOptions": {
"jsx": "react-jsx"
},

Categories

Resources