Testing react components: Jest encountered an unexpected token

无人久伴 提交于 2019-12-12 17:19:06

问题


I am trying to test with Jest, but got an error: Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

I have a photo gallery app and whenever I click on an image, a modal pops up with an image. I want to test that when I click on the image, the popup shows or exists. Is there a way to factor this?

HERE IS MY CODE:

import { shallow, mount, render } from 'enzyme';
import App from '../client/src/components/App';

describe('<PhotoItem />', () => {
  it('should popup image on click', () => {
    const wrapper = shallow(
      <App title="mock" />
    );
    wrapper.find('.item item-0').simulate('click');
    expect('.modal-opactiy').toExist();
  });

HERE is my package.json: "jest": { "verbose": true, "transformIgnorePatterns": ["/node_modules/(?!App)"], "testURL": "http://localhost/photos" }


回答1:


Here it is the same problem: Jest Error Unexpected token on react component

You need to add a .babelrc file with:

{ "presets": ["env","react"] }



回答2:


I solved a similar problem by doing the following:

1- add enzyme setup file and write the following:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

2- add jest configuration to your package.json like that:

"jest": {
 "setupFilesAfterEnv": [
  "./path to your setup file/setupEnzyme.js"
 ]
}

3- add .babelrc file to your root path and write the following in it:

{
    "env": {
        "test": {
            "presets": [
                "@babel/preset-env",
                "@babel/preset-react"
            ]
        }
    }
}

4- if you got an error on "expect" keyword in your test just run npm install -D chai and import the expect function in your test code like that import { expect } from 'chai';

if you still get an error try to install babel dependencies like that npm install -D @babel/core @babel/preset-env @babel/preset-react

hope this helps.



来源:https://stackoverflow.com/questions/51639885/testing-react-components-jest-encountered-an-unexpected-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!