ReactJs: Jest failed to parse a file - reactjs

I'm using react with typecript and after adding swiper dependecy my tests start to fail.
These are my configuration:
jest.config.js:
import type { Config } from '#jest/types';
const config: Config.InitialOptions = {
verbose: true,
transform: {
'^.+\\.ts?$': 'ts-jest',
},
transformIgnorePatterns: ['node_modules/(?!swiper|ssr-window|dom7/)'],
};
export default config;
babel.config.js:
module.exports = {
presets: ['#babel/preset-env', '#babel/preset-react', '#babel/preset-flow'],
plugins: [
'babel-plugin-styled-components',
'#babel/plugin-proposal-class-properties',
],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
'\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
},
transform: {
'^.+\\.ts?$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest',
},
};
package.json:
"jest": {
"moduleNameMapper": {
"swiper/react": "swiper/react/swiper-react.js",
"swiper/css": "swiper/swiper.min.css"
},
"transform": {
"^.+\\.css$": "jest-transform-css"
}
},
"transformIgnorePatterns": "node_modules/(?!(swiper|ssr-window|dom7)/)",

After doing lots of research and applying them, the only solution i found was to downgrade to v6

I actually had the same issue with swiper and these lines in jest.config.js solved it:
transformIgnorePatterns: ['/node_modules/(?!swiper|ssr-window|dom7)'],
moduleNameMapper: {
'swiper/react': ['<rootDir>/node_modules/swiper/react/swiper-react.js'],
},

Related

Jest: Fail upon parsing a file

I'm using react with typecript and after adding swiper dependecy my tests start to fail.
These are my configuration:
jest.config.ts:
import type { Config } from '#jest/types';
const config: Config.InitialOptions = {
verbose: true,
transform: {
'^.+\\.ts?$': 'ts-jest',
},
transformIgnorePatterns: ['node_modules/(?!swiper|ssr-window|dom7/)'],
};
export default config;
babel.config.js
module.exports = {
presets: ['#babel/preset-env', '#babel/preset-react', '#babel/preset-flow'],
plugins: [
'babel-plugin-styled-components',
'#babel/plugin-proposal-class-properties',
],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
'\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
},
transform: {
'^.+\\.ts?$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest',
},
};
package.json
...
"jest": {
"moduleNameMapper": {
"swiper/react": "swiper/react/swiper-react.js",
"swiper/css": "swiper/swiper.min.css"
},
"transform": {
"^.+\\.css$": "jest-transform-css"
}
},
"transformIgnorePatterns": "node_modules/(?!(swiper|ssr-window|dom7)/)",
...

Storyshots Runner does not get called

I am using Storybook with the Storyshots addon and whenever I run the tests, the output is the following.
What is causing the storyshots.test.ts file to not get picked up here?
In [filepath...]
1487 files checked.
testMatch: !**/__utils__/**, /Users/root/dev/repo/storyshots.test.ts - 0 matches
testPathIgnorePatterns: /node_modules/ - 1487 matches
testRegex: - 0 matches
Pattern: - 0 matches
It appears the init file for Storyshots is not getting picked up by the jest.config.
// jest.config.js
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
roots: ['<rootDir>/src/'],
modulePathIgnorePatterns: ['<rootDir>/src/.*/__mocks__'],
globalSetup: './jest.global-setup.js',
testMatch: [
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[tj]s?(x)',
'!**/__utils__/**',
'<rootDir>/storyshots.test.ts'
]
}
// .storybook/main.js
const custom = require("../webpack.common.js");
module.exports = {
stories: [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(ts|tsx)",
],
addons: [
{
name: "#storybook/addon-docs",
options: {
configureJSX: true,
}
},
{
name: "#storybook/addon-essentials",
options: {
/* This panel is disabled due to how we write stories */
actions: false,
},
}
],
webpackFinal: (config) => {
return {
...config,
resolve: {
...config.resolve,
alias: { ...config.resolve.alias, ...custom.resolve.alias },
},
};
},
};
// storyshots.test.ts
import initStoryshots from '#storybook/addon-storyshots'
initStoryshots()

Jest 28 and React: Module imports without file extensions are not working

I've been trying to upgrade jest on my project using the migration guide https://jestjs.io/ro/docs/upgrading-to-jest28
Everything works ok, except for module imports. If the file extension is not specified, I get an error when trying to run the tests
If I specify also the file extension, tests run well.
I checked the jest documentation and I already have the moduleFileExtensions correctly set moduleFileExtensions: ['js', 'jsx', 'json', 'ts', 'tsx'],
This did not happen in Jest 27
module.exports = {
collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.d.ts'],
coveragePathIgnorePatterns: ignorePatterns,
setupFiles: [require.resolve('../polyfills')],
setupFilesAfterEnv: [require.resolve('./setupTests'), userSetupFile].filter(Boolean),
testMatch: [
'<rootDir>/**/__tests__/**/*.{js,jsx,ts,tsx}',
'<rootDir>/**/*.+(spec|test).{js,jsx,ts,tsx}',
'<rootDir>/**/*-specs.{js,jsx,ts,tsx}'
],
testPathIgnorePatterns: ignorePatterns,
testEnvironment: 'jsdom',
testEnvironmentOptions: {pretendToBeVisual: true},
testURL: 'http://localhost',
transform: {
'^.+\\.(js|jsx|ts|tsx)$': require.resolve('./babelTransform'),
'^.+\\.(css|less|sass|scss)$': require.resolve('./cssTransform.js'),
'^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|less|sass|scss|json)$)': require.resolve('./fileTransform')
},
transformIgnorePatterns: [
'^.+\\.module\\.(css|less|sass|scss)$'
],
moduleNameMapper: {
'^.+\\.module\\.(css|less|sass|scss)$': require.resolve('identity-obj-proxy'),
'^#testing-library/jest-dom$': require.resolve('#testing-library/jest-dom'),
'^#testing-library/react$': require.resolve('#testing-library/react'),
'^#testing-library/user-event$': require.resolve('#testing-library/user-event'),
'^react$': require.resolve('react'),
},
moduleFileExtensions: ['js', 'jsx', 'json', 'ts', 'tsx'],
globals,
watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'].map(m => require.resolve(m)),
resetMocks: true
FileTransform.js:
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
return `module.exports = ${assetFilename};`;
}
};

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

jest with typescript throws an error when importing a file

I'm having issues with jest on typescript.
//myprovider.tsx
class MyProvider{
constructor(){}
giveMeFive(): int{ return 5; }
}
export { MyProvider }
// myprovider.test.js
import { MyProvider } from './myprovider';
test('give me five!', () => {
const myprovider = new MyProvider();
/// assert
})
I get the following 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".
import { MyProvider } from './myprovider';
^
I'm not sure what I'm missing, I have this on my package
//package.json
"jest": {
"transform": {
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": ["ts", "tsx", "js"]
},
// .babelrc
{
"presets": [
"#babel/preset-typescript"
]
}
//jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.tsx?$': 'babel-jest',
},
}
Make sure to install these packages:
babel-jest #babel/core #babel/preset-env
Your babel config should look like this:
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current",
},
},
],
"#babel/preset-typescript",
]

Resources