Jest test fails with Unexpected token, expected ";" - javascript

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"
},

Related

cannot find module when using alias with Typescript and Eslint

I have an error when trying to import a ts file using alias.
Cannot find module '#utils/helpers' or its corresponding type declarations.
And also i got no autocompletion is vscode.
I installed tsconfig-paths and eslint-import-resolver-typescript
tsconfig.json file
{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true,
"target": "es6",
"esModuleInterop": true,
"moduleResolution": "node",
"outDir": "dist",
"baseUrl": "./src",
"paths": {
"#utils": ["utils/*"]
},
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
.eslintrc file
{
"root": true,
"parser": "#typescript-eslint/parser",
"plugins": ["#typescript-eslint", "import"],
"extends": ["plugin:#typescript-eslint/recommended", "prettier"],
"rules": {
},
"settings": {
"import/parsers": {
"#typescript-eslint/parser": [".ts"]
},
"import/resolver": {
"typescript": {
"alwaysTryTypes": true,
"project": "tsconfig.json"
}
}
}
}
This is my project structure
Build error
You have configured eslint - that will lint about the #utils existence
You have configured tsconfig - that will auto suggest files inside that directory
But you haven't told JS #utils exists and it's types
To do so, install tsconfig-paths package, this will tell js where to look for #utils
Usage is quite simple, you just put tsconfig-paths/register before your nodemon, here's my package.json
"start": "ts-node -r tsconfig-paths/register src/server",
"dev": "ts-node-dev -r tsconfig-paths/register --respawn src/server",
Or you can put it inside tsconfig.json
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#utils/*": ["utils/*"]
},
},
"ts-node": {
"require": ["tsconfig-paths/register"]
},
"ts-node-dev": {
"require": ["tsconfig-paths/register"]
}
}

How to get CSS modules to work with TypeScript and Rollup?

I am trying to create a shared UI kit amongst multiple websites, and so creating a TypeScript library (for the first time in a while). I have this in my tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": "."
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules"],
"ts-node": {
"compilerOptions": {
"module": "commonjs"
}
}
}
And I have this in my rollup.config.js:
import pkg from './package.json'
import dts from 'rollup-plugin-dts'
import esbuild from 'rollup-plugin-esbuild'
import autoprefixer from 'autoprefixer'
import postcss from 'rollup-plugin-postcss'
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
const name = pkg.main.replace(/\.js$/, '')
export default [
{
preserveModules: true,
input: 'src/index.ts',
plugins: [
peerDepsExternal(),
postcss({
plugins: [autoprefixer()],
sourceMap: true,
extract: false,
modules: true,
}),
esbuild({
include: /\.[jt]sx?$/,
exclude: /node_modules/,
sourceMap: true,
target: 'es6',
jsx: 'transform',
jsxFactory: 'React.createElement',
jsxFragment: 'React.Fragment',
}),
],
output: [
{
dir: 'dist',
exports: 'default',
format: 'cjs',
sourcemap: true,
},
],
external: ['react', 'react-dom'],
},
{
input: 'src/index.ts',
plugins: [dts()],
output: {
file: `${name}.d.ts`,
format: 'es',
},
},
]
And I have this in my package.json:
{
"name": "#myorg/mylib.js",
"version": "0.0.1",
"devDependencies": {
"autoprefixer": "^10.4.11",
"esbuild": "^0.15.7",
"postcss": "^8.4.16",
"rollup": "^2.79.0",
"rollup-plugin-dts": "^4.2.2",
"rollup-plugin-esbuild": "^4.10.1",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-postcss": "^4.0.2",
"typescript": "^4.8.3"
},
"main": "dist/index.js",
"license": "MIT",
"scripts": {
"build": "yarn rollup -c"
},
"peerDependencies": {
"classnames": "^2.3.2",
"next": "^12.3.0",
"react": "^18.2.0"
},
"dependencies": {
"#types/react": "^18.0.20",
"classnames": "^2.3.2"
}
}
And then I am trying to load this src/index.ts:
import Button from './components/Button'
export default {
Button,
}
Which references these two:
import React from 'react'
import styles from './index.module.css'
export default function Button() {
return <button className={styles.button}>hello</button>
}
And index.module.css is:
.button {
background: red;
}
However, I am getting this error on yarn build:
yarn run v1.22.17
$ yarn rollup -c
$ /my/project/node_modules/.bin/rollup -c
src/index.ts → dist...
created dist in 190ms
src/index.ts → dist/index.d.ts...
src/components/Button/index.tsx(4,20): error TS2307: Cannot find module './index.module.css' or its corresponding type declarations.
[!] (plugin dts) Error: Failed to compile. Check the logs above.
src/components/Button/index.tsx
Error: Failed to compile. Check the logs above.
at error (/my/project/node_modules/rollup/dist/shared/rollup.js:198:30)
at throwPluginError (/my/project/node_modules/rollup/dist/shared/rollup.js:21919:12)
at Object.error (/my/project/node_modules/rollup/dist/shared/rollup.js:22641:20)
at Object.error (/my/project/node_modules/rollup/dist/shared/rollup.js:22096:42)
at Object.transform (/my/project/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.cjs:1618:26)
at /my/project/node_modules/rollup/dist/shared/rollup.js:22848:40
Any ideas how to get the CSS modules compiling with Rollup?
In my case, the issue with the #import was solved by removing the extension.
Instead of:
#import 'some.css'
use this:
#import 'react-toastify/dist/ReactToastify'

TSError: ⨯ Unable to compile TypeScript - Jest, Nodejs, Typescript

I'm getting an error when i run the yarn test. Apparently the error is in the jest.cofig.ts in the object "moduleNameMapper".
I think it's in that file because if I remove the line the tests "work" (it doesn't actually test anything, but it doesn't give the error either.)
jest.config.ts
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/en/configuration.html
*/
import { pathsToModuleNameMapper } from 'ts-jest/utils';
import { compilerOptions } from './tsconfig.json';
export default {
preset: 'ts-jest',
transform: {
'^.+\\.ts?$': 'ts-jest',
'^.+\\.js?$': 'babel-jest',
},
verbose: true,
clearMocks: true,
setupFiles: ['<rootDir>/src/tests/index.ts'],
setupFilesAfterEnv: ['<rootDir>/src/tests/setup.ts'],
testEnvironment: 'node',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>' }),
};
tsconfig.json
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": [
"es6"
],
"allowJs": true,
"outDir": "./dist",
"rootDir": "./src",
"removeComments": true,
"typeRoots": [
"./node_modules/#types",
"./src/#types"
],
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"strictPropertyInitialization": false,
"baseUrl": ".",
"paths": {
"#infrastructure/*": ["./src/infrastructure/*"],
"#useCases/*": ["./src/use-cases/*"],
"#tests/*": ["./src/tests/*"],
"#domain/*": ["./src/domain/*"],
"#messagesConsumers/*": ["./src/messages-consumers/*"]
}
},
"include": [
"src/**/*"
]
}
package.json -> scripts
"scripts": {
"tsc": "tsc",
"test": "NODE_ENV=test tsnd -r tsconfig-paths/register --transpile-only src/tests/init.ts",
"test2": "cross-env NODE_ENV=test jest",
"prepare": "husky install && yarn husky set .husky/pre-commit 'yarn lint-staged'",
"setup:dev": "NODE_ENV=development tsnd -r tsconfig-paths/register --transpile-only --ignore-watch node_modules --no-notify src/setup/setup.ts",
"setup:production": "NODE_ENV=production tsnd -r tsconfig-paths/register --transpile-only --ignore-watch node_modules --no-notify src/setup/setup.ts"
},
yarn test error message:
Failed to parse the TypeScript config file /var/www/nodejs/necata-gateway/jest.config.ts
TSError: ⨯ Unable to compile TypeScript:
jest.config.ts:16:24 - error TS2695: Left side of comma operator is unused and has no side effects.
16 moduleNameMapper: (0, utils_1.pathsToModuleNameMapper)(tsconfig_json_1.compilerOptions.paths, { prefix: '<rootDir>' }),
~
at readConfigFileAndSetRootDir (/var/www/nodejs/necata-gateway/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:136:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at readConfig (/var/www/nodejs/necata-gateway/node_modules/jest-config/build/index.js:225:18)
at readConfigs (/var/www/nodejs/necata-gateway/node_modules/jest-config/build/index.js:420:26)
at runCLI (/var/www/nodejs/necata-gateway/node_modules/#jest/core/build/cli/index.js:132:59)
at initialize (/var/www/nodejs/necata-gateway/src/tests/init.ts:29:23)
I still dont understand why this error.... But i changed the object "moduleNameMapper" by removing the function and adding an array with my folder paths.
export default {
preset: 'ts-jest',
transform: {
'^.+\\.ts?$': 'ts-jest',
'^.+\\.js?$': 'babel-jest',
},
verbose: true,
clearMocks: true,
setupFiles: ['<rootDir>/src/tests/index.ts'],
setupFilesAfterEnv: ['<rootDir>/src/tests/setup.ts'],
testEnvironment: 'node',
// moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>' }),
moduleNameMapper: {
// '^#App/(.*)$': '<rootDir>/src/$1',
// '^lib/(.*)$': '<rootDir>/common/$1',
'^#useCases/(.*)$': '<rootDir>/src/use-cases/$1',
'^#tests/(.*)$': '<rootDir>/src/tests/$1',
'^#domain/(.*)$': '<rootDir>/src/domain/$1',
'^#messagesConsumers/(.*)$': '<rootDir>/src/messages-consumers/$1',
'^#infrastructure/(.*)$': '<rootDir>/src/infrastructure/$1',
},
};
And now my tests run...

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

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

Categories

Resources