Jest not transforming esm files - reactjs

Im doing some testing with react testing library to test swiper module in my app but got
export { default as Swiper, default } from './core/core.js';
SyntaxError: Unexpected token 'export'
I tried to apply transformers and add transformIgnorePatterns and none helped me
My jest.config.js
const nextJest = require("next/jest");
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: "./",
});
/** #type {import('jest').Config} */
const customJestConfig = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
moduleNameMapper: {
"^components/(.*)$": "<rootDir>/src/components/$1",
"^data/(.*)$": "<rootDir>/src/data/$1",
"^types/(.*)$": "<rootDir>/src/types/$1",
"^theme/(.*)$": "<rootDir>/src/theme/$1",
"^slices/(.*)$": "<rootDir>/src/slices/$1",
"^store/(.*)$": "<rootDir>/src/store/$1",
"^utils/(.*)$": "<rootDir>/src/utils/$1",
"^contexts/(.*)$": "<rootDir>/src/contexts/$1",
"^theme/(.*)$": "<rootDir>/src/theme/$1",
"^helpers/(.*)$": "<rootDir>/src/helpers/$1",
"^pages/(.*)$": "<rootDir>/src/pages/$1",
"^graphql/(.*)$": "<rootDir>/src/graphql/$1",
"^uuid$": require.resolve("uuid"),
"^swiper$": require.resolve("swiper"),
},
testEnvironment: "jest-environment-jsdom",
transform: {
"(js|jsx|ts|tsx)$": ["babel-jest", { presets: ["next/babel"] }],
},
moduleFileExtensions: ["ts", "tsx", "js", "json", "jsx"],
transformIgnorePatterns: ["node_modules/(?!(swiper))"],
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);

Related

JEST Cannot find module 'typescript-cookie'

I'm trying to run some tests in a project that was created using VITE + TS, and I'm getting the following error:
The module typescript-cookie is the only one it's not being found. If remove this module all tests work fine!
My jest.config.ts
module.exports = {
testEnvironment: 'jest-environment-jsdom',
collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx}'],
coverageDirectory: 'coverage',
setupFilesAfterEnv: ['<rootDir>/src/config/jest-setup.ts'],
transformIgnorePatterns: ['/node_modules/(?!#element)/'],
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
},
moduleNameMapper: {
'#hooks': ['<rootDir>/src/commons/hooks'],
'#contexts': ['<rootDir>/src/commons/contexts'],
'#commons': ['<rootDir>/src/commons'],
'#mock': ['<rootDir>/src/commons/mock'],
'#common/components': ['<rootDir>/src/commons/components'],
'#enum': ['<rootDir>/src/commons/enum/'],
'#interfaces': ['<rootDir>/src/commons/interfaces/'],
'#utils': ['<rootDir>/src/commons/utils/'],
'#mainRoutes': ['<rootDir>/src/router'],
'#services': ['<rootDir>/src/commons/services'],
},
};
vite.config.ts
import react from '#vitejs/plugin-react';
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'#hooks': '/src/commons/hooks',
'#enum': '/src/commons/enum',
'#mock': '/src/commons/mock',
'#common/components': '/src/commons/components',
'#services': '/src/commons/services',
'#common': '/src/commons',
'#contexts': '/src/commons/contexts',
'#interfaces': '/src/commons/interfaces',
'#utils': '/src/commons/utils',
'#mainRoutes': '/src/router',
},
},
});
```
I've been experiencing the same error in a project that was created with Create React App. Assuming it's an issue with the library, I filed a bug report.
https://github.com/carhartl/typescript-cookie/issues/110

React: Jest configuration Issue with Path Aliases

I have set up a React custom boilerplate and it uses Webpack 5, TypeScript and other libs. I am trying to set up Jest but I am getting an error when the test runs that Cannot find module 'utils/constants' from 'src/App.tsx.
It is because of Path Aliases, I guess but I am not sure how to fix this. Can anyone please help me here? Thanks
I am using tsconfig-paths-webpack-plugin for Path Aliases.
webpack.config.js
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.tsx'),
resolve: {
plugins: [new TsconfigPathsPlugin()],
.......
}
.......
}
tsconfig.json
{
"compilerOptions": {
.........
"baseUrl": "./src",
"paths": {
"components/*": ["./components/*"],
"styles/*": ["./styles/*"],
"utils/*": ["./utils/*"]
}
}
.........
}
jest.config.js
/** #type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
moduleNameMapper: {
'\\.(css|less|scss|sss|styl)$': '<rootDir>/node_modules/identity-obj-proxy'
}
};
App.tsx
import { APP_NAME } from 'utils/constants';
export const App = () => (
<h1> {APP_NAME} </h1>
);
App.test.tsx
import { screen, render } from '#testing-library/react';
import { App } from './App';
describe('App Component', () => {
it('should have React Project text', () => {
render(<App />);
expect(screen.getByText('React Project')).toBeTruthy();
});
});
Error
FAIL src/App.test.tsx
Test suite failed to run
Cannot find module 'utils/constants' from 'src/App.tsx'
Require stack:
src/App.tsx
src/App.test.tsx
However, Jest was able to find: 'utils/constants.ts'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'jsx', 'ts', 'tsx', 'json', 'node'].
I added the following configs in jest.config.js and it worked:
/** #type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
moduleNameMapper: {
'\\.(css|less|scss|sss|styl)$': '<rootDir>/node_modules/identity-obj-proxy',
'^components(.*)$': '<rootDir>/src/components$1',
'^styles(.*)$': '<rootDir>/src/styles$1',
'^utils(.*)$': '<rootDir>/src/utils$1'
}
};

Parsing error: "parserOptions.project" has been set for #typescript-eslint/parser. The file does not match your project config: jest.config.js

I created a modularization of the paths in ts.config, however, when I added moduleNameMapper to jest.config.js it returned the error:
Parsing error: "parserOptions.project" has been set for #typescript-eslint/parser.
The file does not match your project config: jest.config.js.
The file must be included in at least one of the projects provided.
.tsconfig.js
{
"compilerOptions": {
...
"paths": {
"#/*": ["*"]
}
...
}
}
jest.config.js
module.exports = {
roots: ['<rootDir>/src'],
collectCoverageFrom: [
'<rootDir>/src/**/*.{ts, tsx}'
],
coverageDirectory: 'coverage',
testEnvironment: 'node',
transform: {
'.+\\.tsx$': 'ts-jest',
'.+\\.ts?$': 'ts-jest'
},
moduleNameMapper: {
'#/(.*)': '<rootDir>/src/$1'
}
}
Exclude jest.config.js in the .eslintignore file

Cannot find module error while import using jest in next.js

I am trying to configure Jest in my Next.js project. In my test file, I have imported my component like import { HamburgerMenu } from './HamburgerMenu.jsx'. In that component, there are so many other imports. Once of them is
import {
checkValidEmail, getNumbers, getFormttedPhoneNo, validateSubscription,
} from 'helpers/utils';
When I run tests, it gives me the following error (which is on above import statement):
Cannot find module 'helpers/utils' from 'components/common/Smart/HamburgerMenu/HamburgerMenu.jsx'
So here are the details.
jest.config.js (at root dir)
module.exports = {
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['/node_modules/', '/.next/'],
transform: {
'^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest'
},
transformIgnorePatterns: [
'/node_modules/',
'^.+\\.module\\.(css|sass|scss)$',
],
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
},
}
I have added jest: true in the ESLint file.
babel.config.js file (at root dir):
module.exports = {
presets: ["next/babel"],
plugins: [["babel-plugin-styled-components", { ssr: true }]]
};
You can try to add
...
moduleDirectories: ['node_modules', '.'],
...
to your jest.config.js

Error of unexpected token import in react jest test

My jest.config.js file contains this data given below.
But when i am running test command it is giving me error of SyntaxError:
Unexpected token import
Error i am getting when i fire test command
const path = require('path');
module.exports = {
bail: true,
rootDir: process.cwd(),
testRegex: '/__tests__/.*\\.test\\.jsx?$',
transform: { '/__tests__/.*': path.resolve(__dirname, 'jest.transform.js'),},
verbose: true,
};
It typically happens when your tests and code are not processed by Babel. Jest is a Node.js application and Node.js doesn't understand import syntax.
I see that you defined your own transform config. Jest documentation says that if you set some value for transform config option it will overwrite defaults and Jest won't preprocess your code using babel-jest.
To fix this issue you need to explicitly define what files to transform via babel-jest:
transform: {
'/__tests__/.*': path.resolve(__dirname, 'jest.transform.js'),
"^.+\\.(js|jsx)$": "babel-jest",
},
Please install "babel-jest": "^23.0.1", and add the following transform config:
const path = require('path');
module.exports = {
bail: true,
rootDir: process.cwd(),
testRegex: '/__tests__/.*\\.test\\.jsx?$',
"transform": {
"\\.js$": "<rootDir>/node_modules/babel-jest"
},
verbose: true,
};
Let me know if the issue still persists

Resources