reactjs - Jest 错误 react 组件上出现意外标记

标签 reactjs jestjs babel-jest

enter image description here

我在运行 npm test 时在 React 组件名称 上收到意外的 token 。尝试阅读其他几个类似的问题,但似乎没有一个对我有用。我在下面添加了 babelrc 、 package.json 和我的测试文件内容

<!-- content of .babelrc file -->
{ "presets": ["env"] }

<!-- content of package.son file -->
  "dependencies": {
    "react": "^16.2.0",
    "react-bootstrap": "^0.32.1",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.1.1",
    "redux": "^3.7.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-jest": "^23.0.0-alpha.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "enzyme-to-json": "^3.3.3",
    "jest": "^22.4.2",
    "react-test-renderer": "^16.2.0"
  },
  "jest": {
    "notify": true,
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "setupTestFrameworkScriptFile": "./src/setupTests.js",
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    }
  }

<!-- Content of Test file App.test.js -->
import React from 'react';
import { shallow, mount } from 'enzyme';
import App from '../../src/components/App';

// describe what we are testing
describe('Render App Component', () => {
 
 // make our assertion and what we expect to happen 
 it('should render without throwing an error', () => {
    wrapper = shallow(<App />);
    expect(wrapper.find('.app__wrapper').length).toEqual(1);
 })
})

最佳答案

以下是我解决该问题的方法。

    • 将以下内容添加到您的 .babelrc 文件中,并确保 .babelrc 位于根文件夹中
{ "presets": ["env","react"] }
    • 确保排除 CSS、图像、SCSS、PDF、字体等静态资源。将以下内容添加到 package.json,如屏幕截图中突出显示的
"moduleNameMapper": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
    "<rootDir>/__mocks__/fileMock.js",
  "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
<小时/>

屏幕截图:

exclude-static-assets

关于reactjs - Jest 错误 react 组件上出现意外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49397368/

相关文章:

javascript - 在更新快速移动的 UI 状态时,如何提高 Redux 的性能?

javascript - Draft-js 编辑器导致反向输入

reactjs - 要求未定义

reactjs - 来自 create-react-app 的 Jest 未在 Windows 上运行

reactjs - 单元测试 - 使用 Jest 和 Enzyme 在 React 中链接

javascript - 我如何将数据从 ReactJS 提交表单传递到 AdonisJS

javascript - 如何使用 Jest 模拟构造函数状态初始化

node.js - 用于监视较低级别方法的 Jest 单元测试 (NodeJS)

typescript - Jest 不会转换模块 - SyntaxError : Cannot use import statement outside a module

javascript - Jest 异步测试忽略expect()函数