酶instance()返回null [英] Enzyme instance() returns null
问题描述
我进行了以下测试:
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?
我知道酶有这个东西:
注意:对于React 16及更高版本,instance()对于无状态返回null 功能组件.
NOTE: With React 16 and above, instance() returns null for stateless functional components.
但是我的功能组件确实有一个状态,我正在使用钩子(如果那会改变任何东西),应该仍然有某种方式可以访问instance.componentMethod()
,对吗?
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?
推荐答案
注意:在React 16及更高版本中,instance()对于无状态功能组件返回null.
NOTE: With React 16 and above, instance() returns null for stateless functional components.
在stateless component
中,它们实际上是指功能组件. instance()
方法是为基于类的组件保留的.
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>;
}
}
但不是这个:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
这篇关于酶instance()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!