当我尝试测试一个非常简单的组件时,我收到了一个contextTypes错误

时间:2016-12-14 03:18:59

标签: reactjs enzyme expectj

我是reactjs的新手,并试图为一个简单的函数编写一个单元测试。 我正在使用酶,这是我的测试:

import React from 'react';
import { shallow } from 'enzyme';
import {P} from "../../src/app/components/T";
import ToDoItem from "../../src/app/components/ToDoItem";

function mockItem(overrides) {
  // … create mock ToDo Item
}

describe('<P />', () => {
  it('renders without exploding', () => {
    const wrapper = shallow(<P attach={ true } />);
    expect(wrapper.length).toEqual(1);
  });
});

这是我的组件:

import  React from "react";

export class T extends  React.Component{
  render() {
    return (
    <div>
        <div className="row panel">
            <div className="col-sm-12 header">uuuuu</div>
        </div>
    </div>
    );
  }
}

但是当我运行它时,我收到以下错误:

<P /> renders without exploding:
 TypeError: Cannot read property 'contextTypes' of undefined
  at ShallowComponentWrapper._maskContext (node_modules\react-dom\lib\ReactCompositeComponent.js:461:33)
  at ShallowComponentWrapper._processContext (node_modules\react-dom\lib\ReactCompositeComponent.js:481:30)
  at ShallowComponentWrapper.mountComponent (node_modules\react-dom\lib\ReactCompositeComponent.js:180:30)
  at Object.mountComponent (node_modules\react-dom\lib\ReactReconciler.js:46:35)
  at ReactShallowRenderer._render (node_modules\react-dom\lib\ReactShallowRenderer.js:126:23)
  at _batchedRender (node_modules\react-dom\lib\ReactShallowRenderer.js:79:12)
  at Object.batchedUpdates (node_modules\react-dom\lib\ReactDefaultBatchingStrategy.js:60:14)
  at Object.batchedUpdates (node_modules\react-dom\lib\ReactUpdates.js:97:27)
  at ReactShallowRenderer.render (node_modules\react-dom\lib\ReactShallowRenderer.js:106:18)
  at ReactShallowRenderer.render (node_modules\enzyme\build\react-compat.js:158:39)
  at node_modules\enzyme\build\ShallowWrapper.js:90:26
  at ReactDefaultBatchingStrategyTransaction.perform (node_modules\react-dom\lib\Transaction.js:140:20)
  at Object.batchedUpdates (node_modules\react-dom\lib\ReactDefaultBatchingStrategy.js:62:26)
  at batchedUpdates (node_modules\react-dom\lib\ReactUpdates.js:97:27)
  at node_modules\enzyme\build\ShallowWrapper.js:89:41
  at withSetStateAllowed (node_modules\enzyme\build\Utils.js:224:3)
  at new ShallowWrapper (node_modules\enzyme\build\ShallowWrapper.js:88:38)
  at shallow (node_modules\enzyme\build\shallow.js:19:10)
  at Context.<anonymous> (C:/tj/reactjs-basics/test/components/test.js:16:25)

我不知道我是否遗漏了任何图书馆,或者我是否在做我的代码。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

我不确定您是否尝试使用该行

const wrapper = shallow(<P/>, { attach: true });

但是根据Enzymes文档(http://airbnb.io/enzyme/docs/api/shallow.html),浅的第二个参数应该是一个带有上下文传递给组件的对象。

如果你试图将它作为道具传递到你的组件中,你应该像这样编写浅层声明:

const wrapper = shallow(<P attach={ true } />);

答案 1 :(得分:0)

您正以错误的方式导入P组件。如果您

export class T extends  React.Component{}

然后导入

import { T } from "../../src/app/components/T";
...
shallow(<T attach={ true } />);

看看这个article它对你有用。

HTH