我在用笑话和酶测试组件时遇到了一些困难。我想做的是测试在 name 字段中提交没有值的表单。这将确保组件显示错误。但是,当我运行其余部分时,我的控制台出现错误:
类型错误:无法读取未定义的属性“值”
我对前端测试和一般测试相当陌生。所以,我不完全确定我是否正确使用酶进行此类测试。我不知道我的测试是否不正确,或者我是否刚刚编写了一个不容易测试的组件。我愿意更改我的组件,这是否会使测试更容易?
零件
class InputForm extends Component {
constructor(props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(e) {
e.preventDefault();
// this is where the error comes from
const name = this.name.value;
this.props.submitForm(name);
}
render() {
let errorMsg = (this.props.validationError ? 'Please enter your name.' : null);
return (
<form onSubmit={(e) => this.onFormSubmit(e)}>
<input
type="text"
placeholder="Name"
ref={ref => {
this.name = ref
}}
/>
<p className="error">
{errorMsg}
</p>
<input
type="submit"
className="btn"
value="Submit"
/>
</form>
);
}
}
InputForm.propTypes = {
submitForm: React.PropTypes.func.isRequired,
};
测试
// all other code omitted
// bear in mind I am shallow rendering the component
describe('the user does not populate the input field', () => {
it('should display an error', () => {
const form = wrapper.find('form').first();
form.simulate('submit', {
preventDefault: () => {
},
// below I am trying to set the value of the name field
target: [
{
value: '',
}
],
});
expect(
wrapper.text()
).toBe('Please enter your name.');
});
});