Testing react components: Jest encountered an unex

2019-07-25 07:30发布

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?

enter image description here 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" }

2条回答
在下西门庆
2楼-- · 2019-07-25 08:05

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.

查看更多
Deceive 欺骗
3楼-- · 2019-07-25 08:11

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

You need to add a .babelrc file with:

{ "presets": ["env","react"] }
查看更多
登录 后发表回答