Mocha无法识别导入中的React

时间:2018-08-28 17:33:26

标签: reactjs webpack mocha babel

我正在尝试将Mocha集成到React / Node应用程序中,但是在我的test.js文件中调用react时遇到了一些麻烦

package.json

{
  "name": "blog_frontend",
  "version": "1.0.0",
  "description": "front end app for react to connect to rails api",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --progress --color --watch --mode=development",
    "test": "./node_modules/mocha/bin/mocha"
  },
  "babel": {
    "presets": [
      "es2015",
      "react"
    ],
    "plugins": "transform-es2015-modules-amd"
  },
  "license": "MIT",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "chai": "^4.1.2",
    "css-loader": "^1.0.0",
    "enzyme": "^3.5.0",
    "html-loader": "^0.5.5",
    "mocha": "^5.2.0",
    "sass-loader": "^7.1.0",
    "sinon": "^6.1.5",
    "style-loader": "^0.21.0",
    "webpack": "^4.17.0",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4"
  },
  "dependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.5",
    "html-webpack-plugin": "^3.2.0",
    "mobx": "^5.0.4",
    "mobx-react": "^5.2.5",
    "node-sass": "^4.9.3",
    "purecss": "^1.0.0",
    "react": "^15.1.0",
    "react-css-modules": "^4.7.7",
    "react-dom": "^15.1.0",
    "react-ellipsis-text": "^1.0.0",
    "react-router": "^3.0.0"
  }
}

test/collection.test.js文件

import React from 'react';
import { mount, shallow } from 'enzyme';
import {expect} from 'chai';

import Collection from '../app/components/Collection.js'

describe('Collection', function() {
  it('should have props for photos', function() {
    const wrapper = shallow(<Collection />); 
    expect(wrapper.props().photos).to.be.defined;
  });
});

error message

error

我尝试了谷歌搜索,但是大多数其他帖子都对import关键字有疑问,而我的专门针对React。我曾尝试在.babelrc中安装其他软件包并调整设置,但没有取得任何成功。任何信息表示赞赏

1 个答案:

答案 0 :(得分:1)

ES模块用于测试中,它们不是本机Node .mjs模块,并且Mocha未配置为使用Babel转换.js文件。经过测试的代码还会有其他问题,例如带有Node本身不支持的类字段。

应将Mocha配置为与Babel一起使用,例如正如the reference所建议的:

"test": "./node_modules/mocha/bin/mocha --require babel-core/register"

还应在项目根目录中访问适当的.babelrc配置。