简体   繁体   中英

Jest test suite failed to run when importing React

I'm trying to run a test on a React component but keep receiving the following error


    /Users/emmy/Desktop/project/__tests__/components/ClientBasket/basket.test.jsx:1
    import React from 'react';
           ^^^^^

    SyntaxError: Unexpected identifier

      at Runtime._execModule (node_modules/jest-runtime/build/index.js:1166:56)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.724 s
Ran all test suites matching /__tests__/i.
(node:79620) ExperimentalWarning: The fs.promises API is experimental 

Test Script:

import React from 'react';
import { shallow } from 'enzyme';
import Basket from '../../src/components/ClientBasket/basket';

const setUp = (props={}) => {
    const component = shallow(<Basket {...props}/>);
    return component;

};

describe('Basket', () => {
    it('should render properly', () => {
        const component = setUp();
        console.log(component.debug())
        const wrapper = component.find('.perproduct')
        expect(wrapper.length).toBe(1);
    })
})

How can I debug this issue? I've tried many things, but I just can't find the solution.

First, you need to have babel-jest setup. ( https://jestjs.io/docs/en/getting-started ).

Second, make sure you are using babel-preset-react ( https://babeljs.io/docs/en/6.26.3/babel-preset-react ). Your babel config should contain '@babel/preset-react' in the presets section.

If you have all of that configured and it's still not working, then you most likely don't have your package.json set up correctly. It should have these lines in the jest configuration to make sure babel plays nicely with jsx files.

    "transform": {
      "\\.js$": "<rootDir>/node_modules/babel-jest",
      "\\.jsx$": "<rootDir>/node_modules/babel-jest"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ]

If you need more help, then you should post your package.json and babel config file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM