如何使用Jest和Enzyme在React中测试表单提交?无法读取未定义的属性'preventDefault'

时间:2017-06-07 17:35:33

标签: javascript reactjs testing jestjs enzyme

我正在编写一个测试来检查如果提交的登录表单没有数据,是否显示错误通知组件。

describe('User signin', () => {
    it('should fail if no credentials are provided', () => {
        const loginComponent = shallow(<Login />);
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit');
        expect(loginComponent.find(Notification).length).toBe(1);
    });
});

看起来.simulate正在测试到达我的handleSubmit函数,但是我在测试中遇到了这个错误:

  

TypeError:无法读取未定义

的属性'preventDefault'

enter image description here

handleSubmit函数

handleSubmit(e) {
    e.preventDefault();  // <-- problem here
    const user = this.state.username;
    const pass = this.state.password;
    const gotoDashboard = () => this.props.history.push('/dashboard');

    const postLogin = (user, pass) => {
        api.userLogin(user, pass)

如果我删除了e.preventDefault();行,我的测试将会过去,但是我需要该行以防止默认的表单提交事件。

1 个答案:

答案 0 :(得分:9)

快速搞清楚......我只需要创建一个带有假冒防御功能的fakeEvent并传递它:

describe('User signin', () => {
    it('should fail if no credentials are provided', () => {
        const fakeEvent = { preventDefault: () => console.log('preventDefault') };
        const loginComponent = shallow(<Login />);
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit', fakeEvent);
        expect(loginComponent.find(Notification).length).toBe(1);
    });
});
相关问题