用酶测试反应组分与上下文:返回一个空物体

时间:2016-10-06 10:23:07

标签: testing reactjs mocha enzyme

我正在尝试用酶对组件执行虚拟测试。测试即将检查上下文。即使我编写与酶文档相同的代码,上下文也总是空的。

import React from 'react';
import { shallow } from 'enzyme';
import Overlay from '../../../../app/components/Overlay/Overlay';


describe('<Overlay />', () => {
  it.only('return a context', () => {
    const wrapper = shallow(<Overlay />, { context: { foo: 10 } });
    console.log(wrapper.context());
    // expect(wrapper.context().foo).to.equal(10);
  });
})

测试的输出是:

<Overlay />
{}
✓ return a context

我哪里错了?

1 个答案:

答案 0 :(得分:4)

由于未给出Overlay组件的详细信息,我假设其中未使用上下文(请检查childContextTypesgetChildContext已正确定义)

例如,请参阅react documents

中的上下文解释

我采用相同的例子来启用测试,

import React from 'react';

export default  class Button extends React.Component {
  render() {
    return (
      <button style={{ background: this.context.color }}>
        {this.props.children}
      </button>
    );
  }
}

Button.contextTypes = {
  color: React.PropTypes.string,
};

class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button>Delete</Button>
      </div>
    );
  }
}

class MessageList extends React.Component {
  getChildContext() {
    return { color: 'purple' };
  }

  render() {
    const children = this.props.messages.map((message) =>
      <Message text={message.text} />
    );
    return <div>{children}</div>;
  }
}

MessageList.childContextTypes = {
  color: React.PropTypes.string,
};

我已经为Button组件创建了测试,如下所示,

import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import Button from '../../src/components/SampleComp';

describe.only('<Button />', () => {
  it('assert for context', () => {
    const wrapper = shallow(
      <Button />,
      { context: { color: 'red' } }
    );
    expect(wrapper.context().color).to.equal('red');
    expect(wrapper.context('color')).to.equal('red');
  });
});
 <Button />
    ✓ assert for context


  1 passing (214ms)

这将正确断言。