Jest在React App

时间:2019-09-04 14:37:50

标签: reactjs jestjs

尝试在React应用程序中使用Jest运行测试时,出现“ Jest遇到意外令牌”错误。

我用npx create-react-app引导了应用程序。 我检查1 + 1 = 2是否有效的简单演示测试。 但是,一旦我要测试组件,就会收到上述错误。

我尝试使用babel.config.js配置babel,并在package.json中添加了jest配置,但仍然存在错误。

这是我的package.json文件:

"dependencies": {
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-icons": "~3.7.0",
    "react-scripts": "~3.1.1",
    "react-validation-framework": "^5.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  },
"jest": {
    "verbose": true,
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/assetTransformer.js",
      "\\.(css|less)$": "<rootDir>/assetTransformer.js"
    }
  },
"devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "babel-jest": "^24.9.0",
    "jest": "^24.9.0",
    "babel-plugin-transform-export-extensions": "^6.22.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react-app": "^9.0.1",
    "enzyme": "~3.10.0",
    "enzyme-adapter-react-16": "~1.14.0",
    "react-test-renderer": "~16.9.0",
    "sinon": "^7.4.2"
  }

我在src / 测试中有一个setupTests.js文件,编写如下:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

我正在测试的组件位于src / App中,如下所示

import React from 'react';
import './App.css';
import UserForm from './components/UserForm'

function App() {
  return (
    <div className="App">
      <UserForm/>
    </div>
  );
}

export default App;

App.test.js在src / 测试中,如下所示:

import React from 'react';
import { shallow } from 'enzyme';
import App from '../App';

describe('First React component test with Enzyme', () => {
   it('renders without crashing', () => {
      shallow(<App />);
    });
});

0 个答案:

没有答案