diff --git a/src/__tests__/setFormikInitialValue.js b/src/__tests__/setFormikInitialValue.js index ce9a8a0..fad47d3 100644 --- a/src/__tests__/setFormikInitialValue.js +++ b/src/__tests__/setFormikInitialValue.js @@ -8,14 +8,22 @@ import { setFormikInitialValue } from "../.."; console.error = jest.fn(); -const setFieldValue = jest.fn(); +let setFieldValue; +let Input; -const withFormikMock = withContext({ formik: PropTypes.object }, () => ({ - formik: { - setFieldValue - } -})); -const Input = compose(withFormikMock, setFormikInitialValue)(TextInput); +beforeEach(() => { + setFieldValue = jest.fn(); + + const withFormikMock = withContext({ formik: PropTypes.object }, () => ({ + formik: { + setFieldValue, + values: { + "this input has been set by formik": "set value" + } + } + })); + Input = compose(withFormikMock, setFormikInitialValue)(TextInput); +}); describe("setFormikInitialValue", () => { it("sets the initial value to ''", () => { @@ -27,4 +35,9 @@ describe("setFormikInitialValue", () => { const wrapper = mount(); expect(wrapper.find(TextInput).props().someProp).toEqual("someValue"); }); + + it("does not set initial value if set by formik, e.g. with initial values", () => { + const wrapper = mount(); + expect(setFieldValue).not.toBeCalled() + }); }); diff --git a/src/setFormikInitialValue.js b/src/setFormikInitialValue.js index f7750db..f6b3803 100644 --- a/src/setFormikInitialValue.js +++ b/src/setFormikInitialValue.js @@ -1,12 +1,17 @@ import React from "react"; import { compose, mapProps } from "recompose"; +import { has } from "lodash"; import withFormik from "./withFormik"; const setFormikInitialValue = WrappedInput => { return class WithFocusProp extends React.PureComponent { constructor(props) { super(props); - props.formik.setFieldValue(props.name, ""); + + const { formik, name } = props; + if (!has(formik.values, name)) { + formik.setFieldValue(name, ""); + } } render() {