Jest encountered an unexpected token?
When I tried to use Jest to test my react component, an error occurred. Then I googled and looked for answer in stackoverflow. Took me hours of searching and finally I solved it.
Below is how I solved it.
Install "@babel/plugin-transform-modules-commonjs", "@babel/preset-env", and "@babel/preset-react"
For Typescript, also install "test-js" and "test-node".
Add babel.config.js file to your root and put the code below in it.
module.exports = { presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'], };
- Add jest.config.js file to your root and put the code below in it.
module.exports = {
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
moduleNameMapper: {
'\\.scss$': 'identity-obj-proxy',
'^@components/(.*)$': '<rootDir>/src/components/$1',
},
collectCoverageFrom: ['<rootDir>/**/*.tsx', '<rootDir>/**/*.ts'],
roots: ['<rootDir>'],
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(ts|tsx)$',
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
};
Hope this post can help you.