使用jest /酶对formik组件进行单元测试

Fab*_*zzi 7 javascript reactjs jestjs enzyme formik

我已经整理了一个很好的基本联系表格.但是我现在需要开始编写我的单元测试,并且遇到了大量问题(比如我到目前为止只能设法获得快照测试).

首先,如果您没有填写所有必需的部分,那么当您单击"提交"按钮时,我正在尝试测试表单应该呈现我的验证消息.

我以为我可以通过调用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');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

这是我的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);
Run Code Online (Sandbox Code Playgroud)

spe*_*.sm 6

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

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

const form = wrapper.find('form');
form.simulate('submit', { preventDefault: () => {} });
Run Code Online (Sandbox Code Playgroud)

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

setTimeout(() => {
  wrapper.update();
}, 0);
Run Code Online (Sandbox Code Playgroud)

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