Reactjs 防止React组件中出现默认问题
我有一个相当基本的反应成分。我正在尝试创建一个提交的表单。当表单提交时,我试图阻止默认的提交行为,就像在React中一样 这是整个组件(这里有redux,但对于这个问题不重要): 忽略空分派。我需要这个先通过。这是怎么回事?有什么想法吗 以下是全部错误:Reactjs 防止React组件中出现默认问题,reactjs,enzyme,Reactjs,Enzyme,我有一个相当基本的反应成分。我正在尝试创建一个提交的表单。当表单提交时,我试图阻止默认的提交行为,就像在React中一样 这是整个组件(这里有redux,但对于这个问题不重要): 忽略空分派。我需要这个先通过。这是怎么回事?有什么想法吗 以下是全部错误: TypeError: Cannot read property 'preventDefault' of undefined 5 | 6 | handleSubmit(event) { > 7 |
TypeError: Cannot read property 'preventDefault' of undefined
5 |
6 | handleSubmit(event) {
> 7 | event.preventDefault();
8 | this.props.dispatch();
9 | }
10 |
以下是测试:
it('dispatches an action when form is submitted', () => {
const spy = jest.fn();
const wrapper = shallow(<App dispatch={spy} />);
const form = wrapper.find('form');
form.simulate('submit');
expect(spy).toHaveBeenCalled();
});
it('提交表单时发送操作',()=>{
const spy=jest.fn();
常量包装器=浅();
const form=wrapper.find('form');
形式。模拟(“提交”);
期望(间谍)。已被调用();
});
Enzyme的simulate
不会模拟事件对象,但您可以自己传递一个(请参见),例如:
你的prod代码看起来不错。这里有一个测试它的沙箱:相反,我认为您有一个测试问题。你能发布你的测试代码吗?我把它添加到了原始的帖子中,这很奇怪。我以前从来没有遇到过酶的问题。不管怎样,这起作用了。谢谢
TypeError: Cannot read property 'preventDefault' of undefined
5 |
6 | handleSubmit(event) {
> 7 | event.preventDefault();
8 | this.props.dispatch();
9 | }
10 |
it('dispatches an action when form is submitted', () => {
const spy = jest.fn();
const wrapper = shallow(<App dispatch={spy} />);
const form = wrapper.find('form');
form.simulate('submit');
expect(spy).toHaveBeenCalled();
});
const mockEvent = { preventDefault: jest.fn() };
form.simulate('submit', mockEvent);