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

问题描述 投票:0回答:1

我试图在一个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 

测试脚本。

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);
    })
})

如何调试这个问题?我试了很多方法,但就是找不到解决方法。

javascript reactjs jestjs enzyme
1个回答
1
投票

首先,你需要设置babel-jest。(https:/jestjs.iodocsengetting-started。).

其次,请确保您使用的是babel-预设-反应 (https:/babeljs.iodocsen6.26.3babel-preset-react。). 您的babel配置应该在预设部分包含"@babelpreset-react"。

如果您已经配置了所有的预设,但仍然无法使用,那么您很可能没有正确设置您的 package.json。在jest配置中应该有以下几行,以确保babel能很好地与jsx文件配合。

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

如果您需要更多的帮助,那么您应该把您的package.json和babel配置文件贴出来。

© www.soinside.com 2019 - 2024. All rights reserved.