1

我正在尝试将上下文传递给 React 组件,但是因为我正在使用 Enzyme 进行测试,所以我想动态地将组件添加到它的父组件中,以便我可以检查它的状态。测试看起来像这样:

describe('<BeaconConfig />', () => {
  it('inherits the config from BeaconConfig', () => {
    mount(<BeaconConfig persistent><div id="parent"></div></BeaconConfig>, { attachTo: document.body });
    const wrapper = mount(<Beacon/>, { attachTo: document.getElementById('parent') });
    expect(wrapper.state('persistent')).to.be(true);
  });
});

测试失败是因为组件状态的persistent属性是,尽管它应该通过上下文继承。BeaconundefinedBeaconConfig

当我在挂载时尝试Beacon直接放入 JSX 中时,BeaconConfig它工作正常,但在这种情况下,Enzyme 不会让我进入Beacon组件状态,因为它不是根。

当我将它动态添加到其父组件时,React 没有将上下文传播到我的组件是否正常?

4

2 回答 2

1

React 不传播上下文是正常的——它不查看 DOM 并以这种方式将其与 VDOM 进行比较。

您需要在初始挂载中将其设为子节点,并使用MountWrapper ( docs.find() ) 的or方法来挖掘子节点,找到 Beacon 并进行断言。.children()

于 2016-06-22T15:39:26.707 回答
0

这是我最终使用的完整测试:

describe('Context', () => {
  let wrapper;
  let parent;
  const open = stub().returns({});
  const mockIndexedDB = { open };
  const config = mount(<BeaconConfig persistent position="bottom" indexedDB={mockIndexedDB} />);

  beforeEach(() => {
    parent = document.createElement('div');
    document.body.appendChild(parent);
    wrapper = mount(<Beacon>some text</Beacon>, {
      attachTo: parent,
      context: config.instance().getChildContext()
    });
  });

  afterEach(() => {
    wrapper.detach();
    document.body.removeChild(document.body.firstChild);
  });

  it('overrides the default values with the context if any', () => {
    expect(wrapper.state('persistent')).to.be(true);
    expect(wrapper.state('position')).to.be('bottom');
    expect(open.calledOnce).to.equal(true);
  });
});

@STRML 有一个很好的建议,但我认为不可能访问非根组件的状态。

相反,我单独实例化BeaconConfig并获取它的子上下文,手动将其传递给Beacon使用. 这将测试创建正确的子上下文并正确使用上下文。它不会测试将配置传递到后者何时是后代,但我们可能认为这是理所当然的,因为它是基本的 React 功能。optionsmountBeaconConfigBeaconBeaconConfigBeacon

于 2016-06-23T08:05:28.850 回答