当节点模块使用es6语法(create-react-app)时,Jest无法运行

时间:2018-12-05 01:23:42

标签: javascript reactjs npm jestjs enzyme

我有一个create-react-app项目,并尝试使用office-ui-fabric-reactJestEnzyme组件进行单元测试。

office-ui-fabric-react的最新版本使用es6语法,并且jest无法运行测试。

import { mount } from "enzyme";
import React from "react";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";

describe("<MessageBar />", () => {
    it("renders message bar correctly", () => {
        const wrapper = mount(<MessageBar messageBarType={MessageBarType.success} />);
        expect(wrapper.find('.ms-MessageBar--success').length).toEqual(1);
    });
});

这是来自create-react-app的package.json文件,几乎没有添加

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "office-ui-fabric-react": "^6.110.1",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "react-scripts": "2.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "@types/enzyme": "3.1.5",
    "@types/enzyme-adapter-react-16": "1.0.1",
    "@types/jest": "23.0.0",
    "@types/react": "16.3.16",
    "@types/react-dom": "16.0.5",
    "@types/react-test-renderer": "^16.0.0",
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.7.0",
    "jest": "^23.6.0"
  }
}

错误 Error from Jest

create-react-app不允许我在jest中为package.json指定ani选项而不弹出。

1 个答案:

答案 0 :(得分:0)

在查看了上面评论中的建议之后,以下设置对我有用:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "office-ui-fabric-react": "^6.110.1",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "react-scripts": "2.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.6.0",
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.7.0",
    "jest": "^23.6.0"
  }
}

在我的测试文件sample-tests.jsx

import Enzyme from "enzyme";
import { mount } from "enzyme";
import React from "react";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib-commonjs/MessageBar";

import Adapter from 'enzyme-adapter-react-16';

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

describe("<MessageBar />", () => {
    it("renders message bar correctly", () => {
        const wrapper = mount(<MessageBar messageBarType={MessageBarType.success} />);
        expect(wrapper.find('.ms-MessageBar--success').length).toEqual(1);
    });
});