L
L
Levin19942018-06-24 00:09:05
JavaScript
Levin1994, 2018-06-24 00:09:05

How to test HOC components (enzyme, jest)?

Help with tests for the HOC component. here is the code

import React, { Component } from 'react';
import { object } from 'prop-types';
import { connect } from 'react-redux';

import { getFormSubmitErrors, getFormSyncErrors, getFormMeta } from 'redux-form';

export default formName => WrappedComponent =>
    connect(state => ({
        submitErrors: getFormSubmitErrors(formName)(state),
        syncErrors: getFormSyncErrors(formName)(state),
        meta: getFormMeta(formName)(state),
    }))(
         class WithValidationErrors extends Component {
            static propTypes = {
                meta: object,
                submitErrors: object,
                syncErrors: object,
            };

            static defaultProps = {
                meta: {},
                submitErrors: {},
                syncErrors: {},
            };

            combineErrors({ submitErrors, meta, syncErrors }) {

                const errorsToShow = {};
                const errorKeys = [...Object.keys(submitErrors), ...Object.keys(syncErrors)];

                errorKeys
                    .filter((value, index, arr) => arr.indexOf(value) === index)
                    .forEach(key => {
                        if (!(meta[key] && meta[key].touched && !meta[key].active)) return;

                        if (key in syncErrors) errorsToShow[key] = syncErrors[key];
                        if (key in submitErrors) {
                            if (key in errorsToShow) {
                                errorsToShow[key] += `; ${submitErrors[key]}`;
                            } else {
                                errorsToShow[key] = submitErrors[key];
                            }
                        }
                    });

                return errorsToShow;
            }

            render() {
                const errorsToShow = this.combineErrors(...this.props);

                return <WrappedComponent {...this.props} errorsToShow={errorsToShow} />;
            }
        }
    );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-06-26
@maxfarseer

First you need to answer the question: what exactly do you want to test.
It seems to me that you can create a mock component (using jest mock) or take your real component and wrap it in a HOC function. In total - you get a "pumped-up component" whose functionality, I think, is what you want to test.
1) you can make a snapshot
2) test combineErrorsToShow
I don’t see more room for testing here. Connect makes no sense to test.
ps I don't think it helped a lot, but it might turn out to reflect in this direction and therefore write something.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question