Unit testing React component ref

房东的猫 提交于 2021-01-28 20:07:12

问题


Right now a component that looks like this:

  class Notification extends Component {
      constructor(props, context) {
        super(props,context);
      }


      render() {
        return (<NotificationSystem ref="notificationSystem"/>);
      }
   }

   export default Notification;

And my unit test is:

    it('should make react notification system referencable', () => {
        const wrapper = mount(renderComponent(Notification));
        expect(wrapper.ref('notificationSystem').length).toEqual(1);
    })

My renderComponent is:

function renderComponent(ComponentClass, props = {}, state = {}) {
    let store = createStore(reducer, state);
    return (
     <Provider store={store}>
        <ComponentClass { ...props } /> 
     </Provider>     
    );
}

Currently running this test is giving me:

Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded 

Any idea how properly test if a component is referenceable?

来源:https://stackoverflow.com/questions/39879176/unit-testing-react-component-ref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!