简体   繁体   English

导入 React 时 Jest 测试套件无法运行

[英]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我正在尝试在 React 组件上运行测试,但不断收到以下错误


    /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.首先,您需要设置 babel-jest。 ( https://jestjs.io/docs/en/getting-started ). 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 ).其次,确保您使用的是 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.你的 babel 配置应该在预设部分包含“@babel/preset-react”。

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.如果您已配置所有这些但仍然无法正常工作,那么您很可能没有正确设置 package.json。 It should have these lines in the jest configuration to make sure babel plays nicely with jsx files.它应该在 jest 配置中包含这些行,以确保 babel 可以很好地处理 jsx 文件。

    "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.如果您需要更多帮助,那么您应该发布您的 package.json 和 babel 配置文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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