aacanakin
aacanakin

Reputation: 2913

Jest test case gives Unexpected token in dynamic import() error

I have generated a react app using create-react-app with react-scripts-ts and ejected to configure webpack. I am using react-async-component to render pages async.

import { asyncComponent } from 'react-async-component';

const AsyncNotFoundPage = asyncComponent({
    resolve: () => import('./NotFoundPage').then(x => x.default)
});

export { AsyncNotFoundPage };

When I start the app, it works as it is expected. It splits the chunks of not found page. However, the following jest test case gives error;

describe('AsyncNotFoundPage Component', () => {

    it('should render async', () => {
        const wrapper = shallow(<AsyncNotFoundPage />);
        expect(wrapper.find(NotFoundPage)).toBeTruthy();
    });
});

It gives the following error;

Unexpected token import

I've tried to add all dynamic import plugins to babel config in package.json. It doesn't work.

Any ideas?

Upvotes: 1

Views: 1995

Answers (1)

hannad rehman
hannad rehman

Reputation: 4341

Install babel-jest

npm install --save-dev babel-jest

Configure .babelrc for env Jest will change your NODE_ENV to "test" and Babel doesn't have any configuration for this env, we normally define Babel config for development and production env. When there is no babel transpilation, import keyword actually becomes undefined as it actually doesn't exist in JS context.

update your .babelrc to match following

{
  "presets": [
    "env",
    "react"
  ],
  "plugins": [
    "transform-class-properties",
    "transform-object-rest-spread"
  ],
  "env": {
    "test": {
      "presets": [
        "env",
        "react"
        ],
      "plugins": [
        "transform-class-properties",
        "transform-object-rest-spread",
        "dynamic-import-webpack"
      ]
    }
  }
}

if you are using some other plugins add them also in the test env

Add jest.congfig.json to project root

{
  "transform": {
    "^.+\\.jsx?$": "babel-jest"
  }
}

OR update your package.Json with jest config

"jest": {
"transform": {
        "^.+\\.jsx?$": "babel-jest"
      }
}

if you are using jest.config.json

"scripts": {
    "test": "jest --config=jest.config.json --watch"
},

else

"scripts": {
        "test": "jest --watch"
    },

Upvotes: 1

Related Questions