mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
Prompted from discussion here: https://github.com/coder/coder/pull/60/files#r792124373 Our current FormTextField implementation requires a [higher-order component](https://reactjs.org/docs/higher-order-components.html), which can be complicated to understand. This experiments with moving it to not require being a HoC. The only difference in usage is that sometimes, you need to provide the type like `<FormTextField<FormValues> form={form} formFieldName="some-field-in-form" />` - but it doesn't require special construction.
76 lines
1.9 KiB
TypeScript
76 lines
1.9 KiB
TypeScript
import { act, fireEvent, render, screen } from "@testing-library/react"
|
|
import { useFormik } from "formik"
|
|
import React from "react"
|
|
import * as yup from "yup"
|
|
import { FormTextField, FormTextFieldProps } from "./FormTextField"
|
|
|
|
namespace Helpers {
|
|
export interface FormValues {
|
|
name: string
|
|
}
|
|
|
|
export const requiredValidationMsg = "required"
|
|
|
|
export const Component: React.FC<Omit<FormTextFieldProps<FormValues>, "form" | "formFieldName">> = (props) => {
|
|
const form = useFormik<FormValues>({
|
|
initialValues: {
|
|
name: "",
|
|
},
|
|
onSubmit: (values, helpers) => {
|
|
return helpers.setSubmitting(false)
|
|
},
|
|
validationSchema: yup.object({
|
|
name: yup.string().required(requiredValidationMsg),
|
|
}),
|
|
})
|
|
|
|
return <FormTextField<FormValues> {...props} form={form} formFieldName="name" />
|
|
}
|
|
}
|
|
|
|
describe("FormTextField", () => {
|
|
describe("helperText", () => {
|
|
it("uses helperText prop when there are no errors", () => {
|
|
// Given
|
|
const props = {
|
|
helperText: "testing",
|
|
}
|
|
|
|
// When
|
|
const { queryByText } = render(<Helpers.Component {...props} />)
|
|
|
|
// Then
|
|
expect(queryByText(props.helperText)).toBeDefined()
|
|
})
|
|
|
|
it("uses validation message when there are errors", () => {
|
|
// Given
|
|
const props = {}
|
|
|
|
// When
|
|
const { container } = render(<Helpers.Component {...props} />)
|
|
const el = container.firstChild
|
|
|
|
// Then
|
|
expect(el).toBeDefined()
|
|
expect(screen.queryByText(Helpers.requiredValidationMsg)).toBeNull()
|
|
|
|
// When
|
|
act(() => {
|
|
fireEvent.focus(el as Element)
|
|
})
|
|
|
|
// Then
|
|
expect(screen.queryByText(Helpers.requiredValidationMsg)).toBeNull()
|
|
|
|
// When
|
|
act(() => {
|
|
fireEvent.blur(el as Element)
|
|
})
|
|
|
|
// Then
|
|
expect(screen.queryByText(Helpers.requiredValidationMsg)).toBeDefined()
|
|
})
|
|
})
|
|
})
|