9

我整理了一个非常基本的联系表格,效果很好。但是我现在需要开始编写我的单元测试并且我遇到了很多问题(就像我到目前为止只设法让快照测试通过)。

因此,首先我试图测试如果您没有填写所有必需的部分,当您单击提交按钮时表单应该呈现我的验证消息。

handleSubmit()我想我可以通过调用函数 来实现这一点,例如:componentRender.find('Formik').instance().props.handleSubmit(badFormValues, { resetForm });

但是,当我运行时componentRender.debug(),我的验证消息没有被呈现。就像没有调用validationSchema函数一样?

有什么特别的事情需要做吗?我觉得这个mapPropsToValues()函数正在工作,从查看它正在填充我传递表单的值的状态对象。我只是不明白为什么似乎跳过了验证?

我已经在这里工作了 2 天,并且无法通过谷歌找到任何好的例子(可能是我的错),所以任何帮助都将不胜感激。

到目前为止,供参考的是测试文件:

import React from 'react';
import { shallow, mount } from 'enzyme';
import { BrowserRouter as Router } from 'react-router-dom';
import PartnerRegistrationForm from 'Components/partner-registration-form/PartnerRegistrationForm';

describe('PartnerRegistrationForm component', () => {
    const formValues = {
        companyName: 'some company',
        countryCode: 'GB +44',
        telNumber: 12345678,
        selectCountry: 'United Kingdom',
        postcode: 'ABC1 234',
        addressSelect: '123 street',
        siteName: 'blah',
        siteURL: 'https://www.blah.com',
        contactName: 'Me',
        email: 'me@me.com',
    };

    const componentShallow = shallow(<PartnerRegistrationForm {...formValues} />);

    describe('Component Snapshot', () => {
        it('should match stored snapshot', () => {
            expect(componentShallow).toMatchSnapshot();
        });
    });

    describe('Component functionality', () => {
        it('should not submit if required fields are empty', () => {
            const badFormValues = {
                companyName: 'some company',
                countryCode: 'GB +44',
                telNumber: 12345678,
            };
            const resetForm = jest.fn();
            const componentRender = mount(
                <Router>
                    <PartnerRegistrationForm {...badFormValues} />
                </Router>,
            );
            componentRender.find('Formik').instance().props.handleSubmit(badFormValues, { resetForm });
            // console.log(componentRender.update().find('.validation-error'));
            // console.log(componentRender.find('Formik').instance());
            // expect(componentRender.find('.validation-error').text()).toEqual('Company Name is required');
        });
    });
});

这是我的withFormik()功能:

const WrappedFormWithFormik = withFormik({
    mapPropsToValues({
        companyName,
        countryCode,
        telNumber,
        selectCountry,
        postcode,
        addressSelect,
        siteName,
        siteURL,
        contactName,
        email,
    }) {
        return {
            companyName: companyName || '',
            countryCode: countryCode || '',
            telNumber: telNumber || '',
            selectCountry: selectCountry || '',
            postcode: postcode || '',
            addressSelect: addressSelect || '',
            siteName: siteName || '',
            siteURL: siteURL || '',
            contactName: contactName || '',
            email: email || '',
        };
    },
    validationSchema, // This is a standard Yup.object(), just importing it from a separate file
    handleSubmit: (values, { resetForm }) => {
        console.log('submitting');
        const {
            companyName,
            countryCode,
            telNumber,
            selectCountry,
            postcode,
            addressSelect,
            siteName,
            siteURL,
            contactName,
            email,
        } = values;

        const emailBody = `Name: ${contactName},`
        + `Email: ${email},`
        + `Company Name: ${companyName},`
        + `Country Code: ${countryCode},`
        + `Telephone Number: ${telNumber},`
        + `Country: ${selectCountry},`
        + `Postcode: ${postcode},`
        + `Address: ${addressSelect},`
        + `Website Name: ${siteName},`
        + `Website URL: ${siteURL}`;

        // TODO set up actual contact submit logic
        window.location.href = `mailto:test@test.com?subject=New partner request&body=${emailBody}`;
        resetForm();
    },
})(PartnerRegistrationForm);

4

2 回答 2

6

如果您尝试通过单击按钮来提交表单,它可能不起作用type="submit"

我发现让它提交(并因此运行验证)的唯一方法是直接模拟它:

const form = wrapper.find('form');
form.simulate('submit', { preventDefault: () => {} });

...此外,您可能需要在 formik 的异步验证和状态更改后使用类似以下内容来更新包装器:

setTimeout(() => {
  wrapper.update();
}, 0);

不要忘记使用done()或异步等待,这样测试就不会提前终止。

于 2018-10-15T18:16:51.727 回答
0

您可以直接使用触发道具prop(key)

wrapper.find(Formik).prop('onSubmit')(args)
wrapper.find(Component).prop('onSubmit')(args)

您也可以模拟onclick使用simulate(event)

const mockHandleSubmit = jest.fn()
const wrapper = shallow(<Form onSubmit={mockHandleSubmit} />)
wrapper.find(SubmitButton).simulate('click')
expect(mockHandleSubmit).toHaveBeenCalled();
于 2021-02-04T01:39:22.777 回答