Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest enzyme shallow unexpected token <

I am trying to use enzyme for testing react components, but cant get started even with the most basic example.

import React from 'react'
import { shallow,render,mount,configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16';
import {LoginPage} from '../../../app/components/login/LoginPage'

configure({ adapter: new Adapter() });

test('should say hello',() => {
    const loginPage = shallow(<LoginPage />)
    expect(loginPage.contains('Hello').toBe(true))
})

when running this, I get the following error:-

Test suite failed to run

    D:/code/github/metallica2/metallica/client/src/app/__tests__/components/login/LoginPage.test.js: Unexpected token (9
:30)
         7 |
         8 | test('should say hello',() => {
      >  9 |     const loginPage = shallow(<LoginPage />)
           |                               ^
        10 |     expect(loginPage.contains('Hello').toBe(true))
        11 | })

What am I doing wrong here ?

Thanks,

Amar

like image 576
Amar Dev Avatar asked Jan 07 '18 13:01

Amar Dev


2 Answers

I was able to solve this issue by introducing the below in the .babelrc

{
  "env": {
    "test": {
      "presets": ["env", "react", "stage-2"],
      "plugins": ["transform-export-extensions"],
      "only": [
        "./**/*.js",
        "node_modules/jest-runtime"
      ]
    }
  }
}

and installing the following dev dependencies:-

"babel-plugin-transform-export-extensions"
"enzyme-adapter-react-16"
"jest-cli"
"react-test-renderer"
like image 74
Amar Dev Avatar answered Sep 18 '22 07:09

Amar Dev


This is an issue with Jest not understanding JSX export.

You can solve this issue by adding the following lines to .babelrc file:

"env": {
    "test": {
      "presets": ["@babel/preset-env", "@babel/preset-react"],
      "plugins": ["transform-export-extensions"],
      "only": [
        "./**/*.js",
        "node_modules/jest-runtime"
      ]
    }
  },

And then installing babel-plugin-transform-export-extensions.

like image 37
codejockie Avatar answered Sep 21 '22 07:09

codejockie