Skip to content
Permalink
Browse files

Fix prepareDataForValidation work with instances (#1949)

* Fix prepareDataForValidation work with instances

* Fix typo
  • Loading branch information...
Andrey-Bazhanov authored and jaredpalmer committed Oct 29, 2019
1 parent 53585cd commit ec7810aebf6ca96c5b24c55389258f7217ef907f
Showing with 39 additions and 3 deletions.
  1. +3 −2 src/Formik.tsx
  2. +36 −1 test/Formik.test.tsx
@@ -1,6 +1,7 @@
import * as React from 'react';
import isEqual from 'react-fast-compare';
import deepmerge from 'deepmerge';
import isPlainObject from 'lodash/isPlainObject';
import {
FormikConfig,
FormikErrors,
@@ -986,7 +987,7 @@ export function validateYupSchema<T extends FormikValues>(
/**
* Recursively prepare values.
*/
function prepareDataForValidation<T extends FormikValues>(
export function prepareDataForValidation<T extends FormikValues>(
values: T
): FormikValues {
let data: FormikValues = {};
@@ -1001,7 +1002,7 @@ function prepareDataForValidation<T extends FormikValues>(
return value !== '' ? value : undefined;
}
});
} else if (typeof values[key] === 'object' && values[key] !== null) {
} else if (isPlainObject(values[key])) {
data[key] = prepareDataForValidation(values[key]);
} else {
data[key] = values[key] !== '' ? values[key] : undefined;
@@ -2,7 +2,12 @@ import * as React from 'react';
import { render, fireEvent, wait } from 'react-testing-library';
import * as Yup from 'yup';

import { Formik, FormikProps, FormikConfig } from '../src';
import {
Formik,
prepareDataForValidation,
FormikProps,
FormikConfig,
} from '../src';
import { noop } from './testHelpers';

jest.spyOn(global.console, 'warn');
@@ -876,6 +881,36 @@ describe('<Formik>', () => {
});
});

describe('prepareDataForValidation', () => {
it('should works correctly with instances', () => {
class SomeClass {}
const expected = {
string: 'string',
date: new Date(),
someInstance: new SomeClass(),
};

const dataForValidation = prepareDataForValidation(expected);
expect(dataForValidation).toEqual(expected);
});

it('should works correctly with mixed data', () => {
const date = new Date();
const dataForValidation = prepareDataForValidation({
string: 'string',
empty: '',
arr: [],
date,
});
expect(dataForValidation).toEqual({
string: 'string',
empty: undefined,
arr: [],
date,
});
});
});

// describe('componentDidUpdate', () => {
// let formik: any, initialValues: any;
// beforeEach(() => {

0 comments on commit ec7810a

Please sign in to comment.
You can’t perform that action at this time.