Created
September 25, 2020 21:05
-
-
Save adamjarling/1b9f5d15d3986556a5462746bc9650e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { Router } from "react-router-dom"; | |
import { render } from "@testing-library/react"; | |
import { useForm, FormProvider } from "react-hook-form"; | |
/** | |
* Testing Library utility function to wrap tested component in React Hook Form | |
* @param {ReactElement} ui A React component | |
* @param objectParameters | |
* @param {Object} objectParameters.defaultValues Initial form values to pass into | |
* React Hook Form, which you can then assert against | |
* @param {Array} objectParameters.toPassBack React Hook Form method names which we'd | |
* like to pass back and use in tests. A primary use case is sending back 'setError', | |
* so we can manually setErrors on React Hook Form components and test error handling | |
*/ | |
export function renderWithReactHookForm( | |
ui, | |
{ defaultValues = {}, toPassBack = [] } = {} | |
) { | |
let reactHookFormMethods = {}; | |
const Wrapper = ({ children }) => { | |
const methods = useForm({ defaultValues }); | |
for (let reactHookFormItem of toPassBack) { | |
reactHookFormMethods[reactHookFormItem] = methods[reactHookFormItem]; | |
} | |
return <FormProvider {...methods}>{children}</FormProvider>; | |
}; | |
return { | |
...render(ui, { wrapper: Wrapper }), | |
reactHookFormMethods, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment