Как реализовать обязательную проверку полей в тестах с редукс-формой? - PullRequest
0 голосов
/ 16 октября 2018

У меня есть избыточная форма, для которой у меня есть правила проверки.

import React from "react";
import PropsTypes from "prop-types";
import {Field, reduxForm} from "redux-form";
import {Button} from "react-bootstrap";
import {utils} from "validation-repo";

import InputField from "../form-fields/InputField";
import "./styles/add-campaign-form.scss";
import "./styles/list-item.scss";

const {validationRules} = utils;

const AddCampaignForm = props => {
    const {handleSubmit, pristine, submitting, onCancel, valid} = props;
    return (
        <form className="add-campaign-form" onSubmit={handleSubmit}>
            <div className="form-field">
                <Field 
                    component={InputField} 
                    label="Campaign name" 
                    name="campaign_name" 
                    type="text" 
                    validate={[validationRules.required]} 
                />
            </div>
            <div className="form-controls">
                <Button onClick={onCancel}>Cancel</Button>
                <Button bsStyle="primary" disabled={!valid || pristine || submitting} type="submit">
                    Add
                </Button>
            </div>
        </form>
    );
};

AddCampaignForm.propTypes = {
    onCancel: PropsTypes.func,
    handleSubmit: PropsTypes.func.isRequired,
    pristine: PropsTypes.bool.isRequired,
    submitting: PropsTypes.bool.isRequired,
    valid: PropsTypes.bool.isRequired,
    surveyType: PropsTypes.string
};

AddCampaignForm.defaultProps = {};

export default reduxForm({form: "addCampaign"})(AddCampaignForm);

Но когда я пытаюсь запустить тест, у меня появляется ошибка

/* eslint-disable no-magic-numbers */
import React from "react";
import {Provider} from "react-redux";
import {MemoryRouter} from "react-router-dom";
import {mount, shallow} from "enzyme";
import {applyMiddleware, compose, createStore} from "redux";
import thunk from "redux-thunk";
import {middleware as beesMiddleware} from "redux-bees";
import {NavItem} from "react-bootstrap";
import {Components, utils} from "validation-repo
";

import rootReducer from "reducers";
import InitiativeCampaignContainer from "./InitiativeCampaignContainer";
import CommonComponents from "commonComponents";

const {AddCampaignForm, CampaignWrapper} = CommonComponents;
const {NavBar} = Components;
const {validationRules} = utils;

describe("<InitiativeCampaignContainer/>", () => {
    const one = 1,
        two = 2,
        zero = 0;

    const store = createStore(rootReducer, compose(applyMiddleware(thunk, beesMiddleware())));

    const data = {
        data: {
            attributes: {
                description: "",
                "initiative-id": 1,
                name: "sample",
                state: "",
                "survey-id": 1
            },
            id: "1",
            type: "campaigns"
        }
    };

    const campignWrapperData = [
        {
            attributes: {
                "created-at": "2018-04-27T09:28:54.126Z",
                description: "test",
                "initiative-id": 1,
                name: "Test",
                state: "ACTIVE",
                "survey-id": null,
                tags: [],
                "updated-at": "2018-04-27T09:28:54.126Z"
            },
            id: "1",
            type: "campaigns"
        },
        {
            attributes: {
                "created-at": "2018-04-30T09:29:10.542Z",
                description: "asad",
                "initiative-id": 1,
                name: "Zasd",
                state: "ACTIVE",
                "survey-id": null,
                tags: [],
                "updated-at": "2018-04-27T09:29:10.542Z"
            },
            id: "2",
            type: "campaigns"
        }
    ];

    const mockResponse = (status, statusText, response) => ({
        headers: [{"Content-type": "application/vnd.api+json"}],
        response,
        status,
        statusText
    });

    it("renders the navbar", () => {
        const wrapper = shallow(
            <MemoryRouter>
                <NavBar homeRoute="/">
                    <NavItem eventKey={1}>Link</NavItem>
                    <NavItem eventKey={2}>Link</NavItem>
                </NavBar>
            </MemoryRouter>
        );
        const wrapperNavItem = wrapper.find(NavBar).at(zero);
        expect(wrapperNavItem.find(NavItem).length).toBe(two);
    });

    it("renders one InitiativeCampaignContainer component", () => {
        const ok = 200;

        window.fetch = jest
            .fn()
            .mockImplementation(
                () => new Promise(() => mockResponse(ok, null, JSON.stringify(data)), () => new Error("Error occured"))
            );
        const wrapper = shallow(
            <Provider store={store}>
                <InitiativeCampaignContainer dispatch={store.dispatch} />
            </Provider>
        );

        expect(wrapper.find(InitiativeCampaignContainer).length).toBe(1);
    });

    it("renders one add campaign component", () => {
        const campaign = {
            data: {
                attributes: {
                    description: "",
                    name: "",
                    state: "ACTIVE"
                },
                relationships: {
                    initiative: {
                        data: {
                            id: 1,
                            type: "initiatives"
                        }
                    }
                },
                type: "campaigns"
            }
        };

        const ok = 200;

        window.fetch = jest
            .fn()
            .mockImplementation(
                () =>
                    new Promise(
                        () => mockResponse(ok, null, JSON.stringify(campaign)),
                        () => new Error("Error occured")
                    )
            );

        /* eslint-disable function-paren-newline */
        const wrapper = mount(
            <Provider store={store}>
                <AddCampaignForm validate={[validationRules.required]} />
            </Provider>
        );
        /* eslint-enable function-paren-newline */
        expect(wrapper.find(AddCampaignForm).length).toBe(1);
    });

    it("render CampaignWrapper", () => {
        const wrapper = shallow(
            <Provider store={store}>
                <InitiativeCampaignContainer dispatch={store.dispatch}>
                    <CampaignWrapper
                        displayFilterForm={true}
                        filteredCampaignList={campignWrapperData}
                        handleSubmit={jest.fn()}
                        onApplyFilter={jest.fn()}
                        onClose={jest.fn()}
                        resetFormData={jest.fn()}
                        showFilterForm={jest.fn()}
                    />
                </InitiativeCampaignContainer>
            </Provider>
        );

        expect(wrapper.find(CampaignWrapper).length).toBe(one);
    });
});

Вот ошибка, которую я получаю

Summary of all failing tests
FAIL src/containers/initiatives/InitiativeCampaignContainer.test.jsx
  ● <InitiativeCampaignContainer/> › renders one add campaign component

    TypeError: validate is not a function

      140 | 
      141 |         /* eslint-disable function-paren-newline */
    > 142 |         const wrapper = mount(
      143 |             <Provider store={store}>
      144 |                 <AddCampaignForm validate={[validationRules]} />
      145 |             </Provider>

Как я могу исправить эту ошибку?

1 Ответ

0 голосов
/ 30 октября 2018

validationRules не похоже на функцию.В ваших тестах, возможно, это должно быть:

<AddCampaignForm validate={[validationRules.required]} />

Если вы хотите пройти все правила, то это должно быть

<AddCampaignForm validate={[...validationRules]} />
...