酶实例()返回 null

IT技术 reactjs redux jestjs enzyme
2022-07-07 23:48:27

我有以下测试:

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
  });
});

知道我在做什么错吗?

我知道Enzyme有这个东西:

注意:对于 React 16 及更高版本,instance() 为无状态功能组件返回 null。

但是我的功能组件确实有一个状态,我正在使用钩子(如果它改变了任何东西)并且应该有一些方法可以访问instance.componentMethod(),对吧?

1个回答

注意:对于 React 16 及更高版本,instance() 为无状态功能组件返回 null。

stateless component它们实际上是指功能组件instance()方法是为基于类的组件保留的。

所以你可以将它用于这个组件:

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

但不适用于这个:

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