Enzyme instance() returns null

寵の児 提交于 2021-01-28 03:03:58

问题


I have the following test:

describe('Form', () => {
  let store;
  let wrapper;

  beforeEach(() => {
    store = mockStore(mockData);
    wrapper = mount(
      <Provider store={store}>
        <Form />
      </Provider>
    );
  });

  it('handleForm calls uses validate() for validation', () => {
    const instance = wrapper.instance();
    const submitFormButton = wrapper.find('.submitFormButton');
    submitFormButton.simulate('click');
    console.log(instance); // null
  });
});

Any idea of what I'm doing wrong exactly?

I know that Enzyme has this thing:

NOTE: With React 16 and above, instance() returns null for stateless functional components.

but my functional component does have a state, I'm using hooks (if that changes anything) and there should be some way to access instance.componentMethod() still, right?


回答1:


NOTE: With React 16 and above, instance() returns null for stateless functional components.

With stateless component they mean actually here functional components. The instance() method is reserved for the class based component.

So you can use it for this component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

But not for this one:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}


来源:https://stackoverflow.com/questions/60561427/enzyme-instance-returns-null

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