[英]Testing React Component with Jest/Enzyme
I am trying to use Enzyme's shallow wrapper to get the instance of my component and calling my class function over it. 我试图使用Enzyme的浅包装器来获取我的组件的实例并调用我的类函数。 It shows me this error: TypeError: tree.instance(...).onCampaignSelected is not a function
它向我显示了这个错误: TypeError:tree.instance(...)。onCampaignSelected不是一个函数
class ToolbarPage extends Component {
constructor(){
super();
this.onCampaignSelected = this.onCampaignSelected.bind(this);
this.state = {
item: null
}
}
onCampaignSelected (item) {
this.setState({item})
}
render () {
return (
<MyComponent onItemSelected={this.onCampaignSelected} />
)
}
}
function mapStateToProps(state){
buttons: state.toolbar.buttons
}
export default connect(mapStateToProps)(ToolbarPage);
My test case looks like this 我的测试用例看起来像这样
import { shallow, mount } from 'enzyme';
import ToolbarPage from './ToolbarPage';
import configureStore from 'configureStore';
const store = configureStore();
const props = {
store,
isLoggedIn: false,
messageCounter: 0
}
describe('<ToolbarPage />', () => {
it('allows to select campaign', () => {
const tree = shallow(<ToolbarPage {...props}/>);
tree.instance().onCampaignSelected();
})
})
I also figured out that it is a wrapped component, so I won't get this function on the wrapped component. 我还发现它是一个包装组件,因此我不会在包装组件上获得此功能。 How do I access this function?
我如何访问此功能?
shallow does not render the full set of components with all of their properties & methods. shallow不会使用其所有属性和方法呈现完整的组件集。 It is intended for basic "did this thing render what I expected?"
它的目的是为了“这个东西是否符合我的预期?” testing.
测试。
mount will give you everything and should allow you to test whatever you need. mount将为您提供一切,并且应该允许您测试您需要的任何内容。 It is very useful for testing event handling & manipulating the state of components to test the interactions between components.
它对于测试事件处理和操作组件状态以测试组件之间的交互非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.