Jest fails to run .tsx files - reactjs

I implemented typescript to my create-react-app project and I can't run jest test files with .jsx suffix to test .tsx files
for example I want to test ConsentContainer.tsx file with ConsentContainer.spec.jsx and I got this error
test/unit/containers/ConsentContainer.spec.jsx
● Test suite failed to run
Jest encountered an unexpected token
.
.
.
Details:
C:\src\containers\ConsentContainer.tsx:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { useEffect, useState }
from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import React from 'react';
2 | import configureStore from 'redux-mock-store';
> 3 | import ConsentContainer from '../../../src/containers/ConsentContainer';
when the files had .jsx suffix jest tests worked properly
but I don't know how to make the configuration
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"es6",
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true
},
"include": [
"src"
]
}
jest.config.json
module.exports = {
verbose: true,
testEnvironment: 'jsdom',
setupFiles: ['raf/polyfill'],
setupFilesAfterEnv: ['./test/jest.test-setup.js'],
moduleFileExtensions: ['js', 'jsx', 'tsx'],
moduleNameMapper: {
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'identity-obj-proxy'
},
testPathIgnorePatterns: ['/node_modules/', '/cypress/', '/.cache/Cypress/3.1.0/Cypress/'],
snapshotSerializers: ['enzyme-to-json/serializer'],
transform: {
'^.+\\.jsx?$': 'babel-jest',
'.+\\.(css|css!|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/assetsTransformer.js'
},
transformIgnorePatterns: [
'/node_modules/(?!(p-retry)/)',
'/dist/'
]
};
babel.config.json
{
"presets": ["#babel/preset-react", "#babel/preset-env", "#babel/preset-typescript"],
"plugins": [
"react-hot-loader/babel",
"transform-object-rest-spread",
["#babel/plugin-transform-runtime", {
"regenerator": true
}],
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
["#babel/plugin-proposal-private-property-in-object", { "loose": true }],
["#babel/plugin-proposal-private-methods", { "loose": true }],
["#babel/plugin-proposal-class-properties", { "loose": true }]
]
}
when I install ts-jest package all my tests are failing not only ones connected with .tsx files

Related

Trying to use react-pdf with typescript

I have a React app built with craco that I want to add react-pdf to display PDF files in a react component.
I'm getting the following error:
I've added the following to the craco.config.js file which apparently replaces the webpack.config
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '#primary-color': '#1c48f2' },
modules: true,
javascriptEnabled: true
}
},
}
},
{ plugin: CracoTerserOverridePlugin }
],
webpack: {
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react"
],
plugins: [
[
"#babel/plugin-proposal-class-properties",
"#babel/plugin-syntax-class-properties"
]
],
},
plugins: process.env.NODE_ENV === 'production' ? [
...
}),
] : [],
}
};
tsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
I've tried positions within this object, but nothing seems to fix it. I'm assuming I need to add something else.
You are targeting "es5" , but you are using a module using "ES6" properties.
privateClassProperties are only available from "ES6"
Is it possible for you to target "ES6" ?
Difficult to tell it is in the tsc transpilation phase or babel phase.
If it is during babel phase, you will need a .babelrc file,
you may need a .babelrc specifying target browser version, if it does not work in tsconfig.json
"presets": [
["babel-preset-env", {
"targets": {
"browsers": "last 2 versions"
},
}]
]

Module Not found error after using the compiled code with tsc command

I moved from babel to tsc to generate the build folder which will be used in another project as a module
So I removed .babelrc and added a tsconfig.json
Previously with babel, the index file generated has code like this
Object.defineProperty(exports, "Button", {
enumerable: true,
get: function () {
return _Button.default;
}
});
...
...
var _Button = _interopRequireDefault(require("./components/Button"));
...
...
With tsc, it generated something like this in index file
const Button_1 = __importDefault(require("components/Button"));
The issue is babel is adding ./ for imports which is working previously. But with tsc those are not added. Does anyone know how to add them?
Here is my tsconfig.json file
{
"compilerOptions": {
"target": "ESNext",
"jsx": "react-jsx",
"module": "commonjs",
"rootDir": "./src",
"baseUrl": ".",
"paths": {
"assets/*": ["./src/assets/*"],
"components/*": ["./src/components/*"],
"constants/*": ["./src/constants/*"],
"contexts/*": ["./src/contexts/*"],
"hooks/*": ["./src/hooks/*"],
"lib/*": ["./src/lib/*"],
"styles/*": ["./src/styles/*"]
},
"allowJs": true,
"checkJs": false,
"outDir": "./build",
"inlineSourceMap": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": false,
},
"include": [
"./src/**/*",
],
"exclude": [
"**/stories.js",
"**/test.js",
"**/*.snap"
]
}
.babelrc file which I deleted
{
"presets": [["#babel/preset-react", { "runtime": "automatic" }], "#babel/preset-flow"],
"plugins": [
"#babel/plugin-transform-modules-commonjs",
"#babel/plugin-proposal-class-properties",
[
"module-resolver",
{
"root": ["."],
"alias": {
"assets": "./src/assets",
"components": "./src/components",
"constants": "./src/constants",
"contexts": "./src/contexts",
"hooks": "./src/hooks",
"lib": "./src/lib",
"styles": "./src/styles"
}
}
],
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-nullish-coalescing-operator"
]
}
Edit: Error that i am getting is
Requests that should resolve in the current directory need to start with './'.

Jest can't run test with methods in .tsx file

Usually I only test files that ends with .ts, but in this case I have a file with utility methods that returns a react element. So in this case my file has a .tsx extension and returns some components from material ui and other libraries.
I was getting an error saying SyntaxError: Cannot use import statement outside a module but I solved it by adding "^.+\\.(ts|js)x?$": "ts-jest" to the transform property of my jest.config.js.
But after that I got another error:
● 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:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• 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:\projetos\COM.FLOU.FrontEnd\node_modules\overlayscrollbars\css\OverlayScrollbars.css:19
html.os-html > .os-host {
^
SyntaxError: Unexpected token '.'
jest.config.ts
import { pathsToModuleNameMapper } from "ts-jest/utils";
import { compilerOptions } from "./tsconfig.paths.json";
export default {
coverageDirectory: "coverage/jest",
testEnvironment: "jsdom",
testMatch: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[tj]s?(x)"],
testPathIgnorePatterns: ["\\\\node_modules\\\\", "<rootDir>/cypress/"],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: "<rootDir>/" }),
transform: {
"^.+\\.jsx?$": "babel-jest",
"^.+\\.(ts|js)x?$": "ts-jest",
".+\\.(css|styl|less|sass|scss)$": "jest-css-modules-transform",
},
};
babel.config.js
// babel.config.js
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-react",
"#babel/preset-typescript",
],
plugins: [
[
"#babel/plugin-transform-runtime",
{
regenerator: true,
},
],
],
};
tsconfig.json
{
"compilerOptions": {
"noImplicitAny": true,
"target": "es5",
"module": "esnext",
"jsx": "react-jsx",
"types": [
"jest"
],
"lib": [
"es6",
"DOM"
],
"outDir": "./dist/",
"rootDir": "./src/",
"sourceMap": true,
"removeComments": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"extends": "./tsconfig.paths.json",
"include": [
"src/**/*"
],
"exclude": [
"jest.config.ts"
]
}
Am I missing any specific configuration?
I solved it by adding an empty styleMock.ts file and adding it to moduleNameMapper on my jest.config.ts file.
styleMock.ts
export default {};
jest.config.ts
import { pathsToModuleNameMapper } from "ts-jest/utils";
import { compilerOptions } from "./tsconfig.paths.json";
export default {
coverageDirectory: "coverage/jest",
testEnvironment: "jsdom",
testMatch: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[tj]s?(x)"],
testPathIgnorePatterns: ["\\\\node_modules\\\\", "<rootDir>/cypress/"],
moduleNameMapper: {
...pathsToModuleNameMapper(compilerOptions.paths, { prefix: "<rootDir>/" }),
"\\.(css)$": "<rootDir>/styleMock.ts",
},
transform: {
"^.+\\.(ts|js)x?$": "ts-jest",
},
};

Using jsx-react includes React into the bundle

I'm trying to make React UI component libraries. In my tsconfig, if I set {..., "jsx": "react-jsx"}, I see in the bundle index.esm.js that React code is included.
But if I use the old jsx {"jsx": "react"}, React code is not included in the bundle.
I am using rollup to bundle. This is rollup.config.ts
export default {
input: "./index.ts",
output: [
{
file: pkg.main,
format: "cjs",
},
{
file: pkg.module,
format: "es",
},
],
external: ["react", "react-dom", "#emotion", "#mui/material", "#mui/style"],
plugins: [
resolve(),
external(),
commonjs(),
typescript({
useTsconfigDeclarationDir: true,
}),
terser(),
],
};
This is tsconfig
{
"compilerOptions": {
"declaration": true,
"declarationDir": "lib/types",
"esModuleInterop": true,
"moduleResolution": "Node",
"jsx": "react-jsx",
"resolveJsonModule": true,
"strict": true,
"target": "ESNext"
},
"include": ["./**/*"],
"exclude": ["./**/*.stories.tsx", "./lib", "./node_modules"]
}
How can I use the react-jsx and not include the React code in the bundle. I tried setting sideEffects:false in package.json but it did not work.

Exported modules returns undefined when used react's syntax

I'm using next.js and Typescript, everything compiles fine, when I try to follow any page I see in console (SSR from next) errors which occurred by undefined imports.
I got that any .tsx file that contains react-syntax (<div />) returns undefined if imported as module. And even if I don't export the component and try to export something else (like string) it still returns undefined.
If I use statefull component and return null from renderer - it works fine and module returns function.
My .babelrc:
{
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
"babel-plugin-styled-components",
[
"#babel/plugin-proposal-decorators",
{ "legacy": true }
],
[
"#babel/plugin-proposal-class-properties",
{ "loose": true }
],
[
"module-resolver",
{
"alias": {
"Components": "./build/components",
"UI": "./build/uikit",
"Utils": "./build/utils",
"Hooks": "./build/hooks",
"Contexts": "./build/contexts"
}
}
]
],
"env": {
"test": {
"plugins": [
"#babel/plugin-transform-typescript",
[
"module-resolver",
{
"alias": {
"Components": "./src/components",
"UI": "./src/uikit",
"Utils": "./src/utils",
"Hooks": "./src/hooks",
"Contexts": "./src/contexts",
"Models": "./src/models",
"Mocks": "./src/__mocks__"
}
}
]
]
}
}
}
My tsconfig.json:
{
"compilerOptions": {
"typeRoots": ["./node_modules/#types", "./src/**/*.d.ts"],
"lib": ["dom", "dom.iterable", "esnext"],
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./build",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"esModuleInterop": true,
"sourceMap": true,
"jsx": "preserve",
"skipLibCheck": true,
"pretty": true,
"baseUrl": "./",
"paths": {
"Components/*": ["./src/components/*"],
"Utils/*": ["./src/utils/*"],
"Hooks/*": ["./src/hooks/*"],
"UI/*": ["./src/uikit/*"],
"Contexts/*": ["./src/contexts/*"],
"Models/*": ["./src/models/*"],
"Mocks/*": ["./src/__mocks__/*"]
},
"allowJs": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": false,
"resolveJsonModule": true,
"isolatedModules": true
},
"include": ["./src/**/*"],
"exclude": ["./node_modules"]
}
next.config.js is regular one, nothing used to extend functionality.
Previously everything worked fine, but I've integrated eslint instead of tslint and had much corrections.
I resolved the problem by changing tsconfig.json parameter target to es2020 and module to esnext, so for some reason it works fine now.
I had the problem above because I need to parse ts to es5 because I start the server by regular node command ./server/index.js (no imports will be understand).
So now I have 2 tsconfig.json files with server and client configurations

Resources