Jest encountered an unexpected token?

·

1 min read

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.

  1. Install "@babel/plugin-transform-modules-commonjs", "@babel/preset-env", and "@babel/preset-react"

    For Typescript, also install "test-js" and "test-node".

  2. 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'],
    };
    
  3. 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.