我很难用开玩笑和酶来测试组件。我想做的是测试在名称字段中没有值的情况下提交表单。这将确保组件显示错误。但是,当我运行其余的时,我会在控制台上遇到错误:
typeError:无法读取未定义的属性'值
我是前端测试和总体测试的新手。因此,我不确定我正确使用酶进行此类测试。我不知道我的测试是否不正确,或者我只是编写了不容易测试的组件。我愿意更改组件,如果可以更容易测试?
组件
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,
};
test
// 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.');
});
});
我认为您不需要通过事件对象来模拟提交事件。这应该起作用。
describe('the user does not populate the input field', () => {
it('should display an error', () => {
const form = wrapper.find('form').first();
form.simulate('submit');
expect(
wrapper.find('p.error').first().text()
).toBe('Please enter your name.');
});
});
作为经验法则,您应该尽可能避免使用Refs,为什么?这里
在您的情况下,我建议最好的方法之一是:
class InputForm extends Component {
constructor(props) {
super(props);
this.state = {
name : ''
}
this.onFormSubmit = this.onFormSubmit.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
}
handleNameChange(e){
this.setState({name:e.target.value})
}
onFormSubmit(e) {
e.preventDefault();
this.props.submitForm(this.state.name);
}
render() {
let errorMsg = (this.props.validationError ? 'Please enter your name.' : null);
return (
<form onSubmit={(e) => this.onFormSubmit(e)}>
<input
type="text"
placeholder="Name"
onChange={this.handleNameChange}
/>
<p className="error">
{errorMsg}
</p>
<input
type="submit"
className="btn"
value="Submit"
/>
</form>
);
}
}
我想这将解决您的问题。因此,您的测试应运行良好。
已经在此线程中讨论了问题。
这个解决方案对我有用。
import { mount, shallow } from 'enzyme';
import InputForm from '../InputForm':
import React from 'react';
import { spy } from 'sinon';
describe('Form', () => {
it('submit event when click submit', () => {
const callback = spy();
const wrapper = mount(<InputForm />);
wrapper.find('[type="submit"]').get(0).click();
expect(callback).to.have.been.called();
});
});
它使用摩卡郡 柴而不是开玩笑。但是您可以了解如何做。