【问题标题】:Testing react components: Jest encountered an unexpected token测试反应组件:Jest 遇到了一个意外的令牌
【发布时间】:2019-01-09 09:57:01
【问题描述】:

我正在尝试使用 Jest 进行测试,但出现错误: Jest 遇到了意外的令牌 这通常意味着您正在尝试导入 Jest 无法解析的文件,例如它不是纯 JavaScript。

我有一个照片库应用程序,每当我单击图像时,都会弹出一个带有图像的模式。我想测试当我单击图像时,弹出窗口显示或存在。有没有办法解决这个问题?

这是我的代码:

import { shallow, mount, render } from 'enzyme';
import App from '../client/src/components/App';

describe('<PhotoItem />', () => {
  it('should popup image on click', () => {
    const wrapper = shallow(
      <App title="mock" />
    );
    wrapper.find('.item item-0').simulate('click');
    expect('.modal-opactiy').toExist();
  });

这里是我的 package.json: "jest": { "verbose": true, "transformIgnorePatterns": ["/node_modules/(?!App)"], "testURL": "http://localhost/photos" }

【问题讨论】:

    标签: javascript reactjs jestjs enzyme package.json


    【解决方案1】:

    这里也是同样的问题:Jest Error Unexpected token on react component

    你需要添加一个 .babelrc 文件:

    { "presets": ["env","react"] }
    

    【讨论】:

      【解决方案2】:

      我通过执行以下操作解决了类似的问题:

      1-添加酶设置文件并编写以下内容:

      import Enzyme from 'enzyme';
      import Adapter from 'enzyme-adapter-react-16';
      
      Enzyme.configure({ adapter: new Adapter() });
      

      2- 像这样将 jest 配置添加到您的 package.json 中:

      "jest": {
       "setupFilesAfterEnv": [
        "./path to your setup file/setupEnzyme.js"
       ]
      }
      

      3- 将 .babelrc 文件添加到你的根路径并在其中写入以下内容:

      {
          "env": {
              "test": {
                  "presets": [
                      "@babel/preset-env",
                      "@babel/preset-react"
                  ]
              }
          }
      }
      

      4- 如果您在测试中遇到“expect”关键字错误,只需运行npm install -D chai 并在您的测试代码中导入expect 函数,如import { expect } from 'chai';

      如果仍然出现错误,请尝试安装类似 npm install -D @babel/core @babel/preset-env @babel/preset-react 的 babel 依赖项

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2019-10-07
        • 1970-01-01
        • 1970-01-01
        • 2019-03-22
        • 2020-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多