Jest encountered an unexpected token. ReactJS and axios issue

59 views Asked by At

I'm building an application with ReactJS and trying to do the tests with Jest. However when running "npm run test" I get the following error:

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

followed by the specific issue:

SyntaxError: Cannot use import statement outside a module

  1 | import React from 'react';
  2 | import { render, screen, fireEvent, waitFor } from '@testing-library/react';
> 3 | import axios from 'axios';
    | ^
  4 | import Income from '../src/components/Income';
  5 |
  6 | jest.mock('axios');

this is my jest.config.js :

module.exports = {
  testEnvironment: 'node',
  transform: {
    '^.+\\.(js|jsx)?$': 'babel-jest',
  },
};

and my 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',
    '@babel/plugin-transform-modules-commonjs',
  ],
};

Anyone know how to fix this? Thank you!

I tried forcing this into Jest through the package.json:

  "jest": {
    "moduleNameMapper": {
      "^axios$": "axios/dist/node/axios.cjs"
    }
  }
0

There are 0 answers