【问题标题】:How to test form submission in React with Jest and Enzyme? Cannot read property 'preventDefault' of undefined如何在 React with Jest 和 Enzyme 中测试表单提交?无法读取未定义的属性“preventDefault”
【发布时间】:2017-11-09 04:48:50
【问题描述】:

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

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”

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(); 行,我的测试将通过,但是我需要该行以防止默认的表单提交事件。

【问题讨论】:

    标签: javascript reactjs testing jestjs enzyme


    【解决方案1】:

    很快就想通了...我只需要使用假的 preventDefault 函数创建一个 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);
        });
    });
    

    【讨论】:

    • 这个loginComponent.find('.form-login').dispatchEvent(new Event('submit')); 也有用吗?
    • 是否仍会阻止默认设置,或者测试会导致重定向并重新加载?
    • 如何从表单节点获取值?
    猜你喜欢
    • 1970-01-01
    • 2021-05-08
    • 2017-12-30
    • 2018-10-27
    • 2019-12-24
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多