用Jest/Enzyme测试React组件 [英] Testing React Component with Jest/Enzyme
问题描述
我正在尝试使用Enzyme的浅层包装来获取组件的实例并对其调用类函数.它向我显示此错误: TypeError:tree.instance(...).onCampaignSelected不是函数
I am trying to use Enzyme's shallow wrapper to get the instance of my component and calling my class function over it. It shows me this error: TypeError: tree.instance(...).onCampaignSelected is not a function
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. 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. It is very useful for testing event handling & manipulating the state of components to test the interactions between components.
这篇关于用Jest/Enzyme测试React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!