反应更高阶组件的正确语法

时间:2016-11-24 13:50:40

标签: reactjs

我有以下测试有效:

describe('<UploadForm />', ()=> {
  it('should render a <Form />', () => {
    const wrapper = mount(
      <Provider store={store}>
        <UploadForm />
      </Provider>
    );

    expect(wrapper.find('form').length).to.equal(1);
  });
})

然后我想将表单的包装移到更高阶的函数中。

export function TestWrapper(WrappedComponent) {
  return class extends React.Component {
    render() {
      return (
        <Provider store={store}>
          <WrappedComponent />
        </Provider>
      );
    };
  }
}

我的调用代码如下所示:

describe('<UploadForm />', ()=> {
  it('should render a <Form />', () => {
    const wrapper = mount(
      TestWrapper(UploadForm)
    );

    expect(wrapper.find('form').length).to.equal(1);
  });
})

但我收到此错误消息:

VM456 context.js:219 Warning: Failed prop type: The prop `Component` is marked as required in `<<anonymous>>`, but its value is `undefined`.
    in UnknownlocalConsole.(anonymous function) @ VM456 context.js:219printWarning @ warning.js:36warning @ warning.js:60checkReactTypeSpec @ checkReactTypeSpec.js:80validatePropTypes @ ReactElementValidator.js:151createElement @ ReactElementValidator.js:187ReactWrapper @ ReactWrapper.js:94mount @ mount.js:19(anonymous function) @ UploadForm-test.js:31callFn @ VM460 mocha.js?bc2b9e2…:4445Runnable.run @ VM460 mocha.js?bc2b9e2…:4437Runner.runTest @ VM460 mocha.js?bc2b9e2…:4934(anonymous function) @ VM460 mocha.js?bc2b9e2…:5040next @ VM460 mocha.js?bc2b9e2…:4851(anonymous function) @ VM460 mocha.js?bc2b9e2…:4861next @ VM460 mocha.js?bc2b9e2…:4785(anonymous function) @ VM460 mocha.js?bc2b9e2…:4829timeslice @ VM460 mocha.js?bc2b9e2…:82
VM456 context.js:219 Warning: Failed prop type: The prop `props` is marked as required in `<<anonymous>>`, but its value is `undefined`.
    in UnknownlocalConsole.(anonymous function) @ VM456 context.js:219printWarning @ warning.js:36warning @ warning.js:60checkReactTypeSpec @ checkReactTypeSpec.js:80validatePropTypes @ ReactElementValidator.js:151createElement @ ReactElementValidator.js:187ReactWrapper @ ReactWrapper.js:94mount @ mount.js:19(anonymous function) @ UploadForm-test.js:31callFn @ VM460 mocha.js?bc2b9e2…:4445Runnable.run @ VM460 mocha.js?bc2b9e2…:4437Runner.runTest @ VM460 mocha.js?bc2b9e2…:4934(anonymous function) @ VM460 mocha.js?bc2b9e2…:5040next @ VM460 mocha.js?bc2b9e2…:4851(anonymous function) @ VM460 mocha.js?bc2b9e2…:4861next @ VM460 mocha.js?bc2b9e2…:4785(anonymous function) @ VM460 mocha.js?bc2b9e2…:4829timeslice @ VM460 mocha.js?bc2b9e2…:82
VM456 context.js:219 Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

1 个答案:

答案 0 :(得分:1)

在您的工作测试中,您向React.Component提供了mount() 实例,在您的测试中,您提供了React.Component 类< / em>(从TestWrapper()返回)。你不应该像这样实例化吗?

const WrappedComponent = TestWrapper(UploadForm);
mount(<WrappedComponent />);