如何测试没有传递到包装组件的React HOC函数?



我有一个这样的HOC,我想测试getStuff2函数:

function withHoc(aComponent) {
class hocClass extends React.Component {
getStuff1 = () => {
}
getStuff2 = () => {
}
render() {
return <aComponent {...this.props} getStuff1={this.getStuff1} />;
}
}
}

我像这样测试它:

class MockApp extends React.PureComponent {
render() {
return <p>Hello from your Mock App</p>;
}
}
const MockWithHOC = withHoc(MockApp);
const wrapper = shallow(<MockWithHOC />);
it('Test getStuff2', () => {
const result = wrapper.getStuff2();
});

但是当我运行这个时,它说没有找到getStuff2。当我打印出包装器时,我只看到我在渲染时传入的getStuff1:

<MockApp getStuff1={[Function]} />

我不想将getStuff2传递到包装的组件中,因为那里不需要它。它只需要作为getStuff1的辅助方法,所以有没有一种方法可以访问该方法而不将其传递到包装的组件?

(我假设您正在使用酶,因为您正在使用shallow())

你可以使用wrapper.instance():

const result = wrapper.instance().getStuff2();
<<p>看到em> ShallowWrapper .instance ()

相关内容

最新更新