【发布时间】:2018-05-07 20:32:52
【问题描述】:
我需要访问内部组件的状态,使其激活点击事件,我的问题是使用mount时Enzyme不允许这样做,这只能通过shallow渲染酶来实现,如上所述在here 上,也如前所述,我尝试使用dive 获取Form 组件,然后再次从Form 获取我需要到达的Button 组件,问题是我的测试用例不断失败,因为Form 组件长度为零。
酶:3.1.0
enzyme-adapter-react-15: 1.0.1"
我是Enzyme 的新手,任何帮助将不胜感激,谢谢
contactus.test.js:
test('It should simulate submit action ', ()=>{
let contactUs = shallow(<ContactUs />);
sinon.spy(ContactUs.prototype, 'submitMessage');// Verify this method call
let form = contactUs.find(Form)
expect(form.length).toBe(1);//Failing over here
let button = form.dive().find(Button);
expect(button.length).toBe(1);
button.setState({disabled : false});//Need to achieve this
expect(button).toBeDefined();
expect(button.length).toBe(1);
expect(button.props().label).toBe('SEND MESSAGE');
button.find('a').get(0).simulate('click');
expect(ContactUs.prototype.submitMessage).toHaveProperty('callCount',
1);
});
contactus.js:
import React, {Component,PropTypes} from 'react';
import Form from './form';
import {sendSubscriptionMessage} from '../../network';
import Button from '../Fields/Button';
export default class ContactUs extends Component {
constructor(props) {
super(props);
this.state = {
contactData: {}
}
}
onChangeHandler(event) {
let value = event.target.value;
this.state.contactData[event.target.name] = value;
}
submitMessage(event) {
event.preventDefault();
sendSubscriptionMessage(this.state.contactData);
}
render() {
return (<div className = "row pattern-black contact logo-container" id = "contact">
<div className = "container" >
<h2 className = "sectionTitle f-damion c-white mTop100" >
Get in Touch!
<Form onChangeHandler = {
this.onChangeHandler.bind(this)
} >
<Button onClick = {
this.submitMessage.bind(this)
}
className = "gradientButton pink inverse mTop50"
label = "SEND MESSAGE" / >
</Form> </div>
</div>
);
}
}
【问题讨论】:
-
为了最大化获得帮助的机会,我建议将代码减少到问题的核心并提供测试代码。