我有以下组件:
GenericButton:
render() {
return(
<span>
<Button ... props... />
{this.renderModalIfNeeded()}
</span>);
}
renderModalIfNeeded() {
if (this.props.modalConfirm) {
return <BasicModal ref={(component) => this.modal = component}
title="Confirm"
body={this.props.modalText}
buttons={[
{
id: "Cancel_"+this.props.id,
text : 'Cancel',
style : 'grey'
},
{
id: "Confirm"+this.props.id,
text : 'OK',
action : () => this.props.action()
}
]}/>;
}
}
BasicModal:
renderButtons() {
return this.props.buttons
.map((button) => {
const previousAction = button.action;
button.action = () => {
if (previousAction) {
previousAction();
}
this.close();
};
return button;
})
.map((button, count) => <GenericButton key={"Button_"+count+"_"+this.props.id} {...button} />);
}
render() {
return (
<Modal show={this.state.showModal} onHide={::this.close}>
<Modal.Header closeButton>
<Modal.Title>{this.props.title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.props.body}
</Modal.Body>
<Modal.Footer>
{this.renderButtons()}
</Modal.Footer>
</Modal>
);
}
我有这个测试,我试图验证模态中的按钮是否正确显示(this.renderButtons()
中的按钮)
describe('Given modal requirements', () => {
const text = "Ne me mori facias";
const id = "Generosa";
const innerModal = mount(<GenericButton id={id} modalConfirm={true} modalText={text}/>).find('BasicModal').first();
it('has two buttons', () => {
const cancelButton = <GenericButton id={"Cancel_"+id} text="Cancel" style="grey"/>;
const okButton = <GenericButton id={"Confirm_"+id} text="OK" action={() => {}} />;
const extractModalBody = (modal) => {
return modal.find('BasicModal').first().find('Modal');
};
expect(extractModalBody(innerModal)).toContainReact(cancelButton);
expect(extractModalBody(innerModal)).toContainReact(okButton);
});
});
如果在测试中我尝试使用BasicModal
检查.debug()
组件的内容,我会收到以下信息:
<BasicModal title="Confirm" body="Ne me mori facias" buttons={{...}}>
<Modal show={false} onHide={[Function]}>
<Modal show={false} onHide={[Function]} backdrop={true} keyboard={true} autoFocus={true} enforceFocus={true} manager={{...}} renderBackdrop={[Function]} animation={true} dialogComponentClass={[Function]} bsClass="modal">
<Modal onHide={[Function]} keyboard={true} autoFocus={true} enforceFocus={true} manager={{...}} renderBackdrop={[Function]} show={false} onEntering={[Function]} onExited={[Function]} backdrop={true} backdropClassName="modal-backdrop" containerClassName="modal-open" transition={[Function]} dialogTransitionTimeout={300} backdropTransitionTimeout={150} />
</Modal>
</Modal>
</BasicModal>
我该如何检查按钮是否实际呈现?
答案 0 :(得分:0)
尝试使用.render()
它会向渲染的React Component DOM返回一个cheerio ..
https://github.com/airbnb/enzyme/blob/master/docs/api/ReactWrapper/render.md
在文档中
.render() => CheerioWrapper
返回当前渲染的HTML周围的CheerioWrapper 节点的子树。
注意:只能在单个节点的包装器上调用。
<强>返回强>
String:生成的HTML字符串
示例:强>
const wrapper = mount(<Bar />); expect(wrapper.find(Foo).render().find('.in-foo')).to.have.length(1);