test: Unit Tests for FormBuilderField and BookingFields components (#16162)
* Remove use of location from FormBuilder * Add tests * FormBuilderField and BookingFields tests * More tests * Remove always true if condition * Fix ui import mockig that got broken after the last merge
This commit is contained in:
1 parent
263a96e660
commit
28c631e108
17 files changed
+365
-318
No files matched your search
@@ -118,7 +118,7 @@ const TextWidget = (props: TextLikeComponentPropsRAQB) => {
|
||||
containerClassName="w-full"
|
||||
type={type}
|
||||
value={textValue}
|
||||
labelSrOnly={noLabel}
|
||||
noLabel={noLabel}
|
||||
placeholder={placeholder}
|
||||
disabled={readOnly}
|
||||
onChange={onChange}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import "@calcom/ui/__mocks__/ui";
|
||||
|
||||
import { TooltipProvider } from "@radix-ui/react-tooltip";
|
||||
import { render, fireEvent, screen } from "@testing-library/react";
|
||||
import * as React from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { getBookingFieldsWithSystemFields } from "../../../lib/getBookingFields";
|
||||
import { BookingFields } from "./BookingFields";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type FormMethods = UseFormReturn<any>;
|
||||
|
||||
const renderComponent = ({
|
||||
props: props,
|
||||
formDefaultValues,
|
||||
}: {
|
||||
props: Parameters<typeof BookingFields>[0];
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
formDefaultValues?: any;
|
||||
}) => {
|
||||
let formMethods: UseFormReturn | undefined;
|
||||
const Wrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
const form = useForm({
|
||||
defaultValues: formDefaultValues,
|
||||
});
|
||||
formMethods = form;
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<FormProvider {...form}>{children}</FormProvider>
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
const result = render(<BookingFields {...props} />, { wrapper: Wrapper });
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return { result, formMethods: formMethods! };
|
||||
};
|
||||
|
||||
describe("BookingFields", () => {
|
||||
it("should correctly render with location fields", () => {
|
||||
const AttendeePhoneNumberOption = {
|
||||
label: "attendee_phone_number",
|
||||
value: "phone",
|
||||
};
|
||||
|
||||
const OrganizerLinkOption = {
|
||||
label: "https://google.com",
|
||||
value: "link",
|
||||
};
|
||||
|
||||
const locations = [
|
||||
{
|
||||
type: AttendeePhoneNumberOption.value,
|
||||
},
|
||||
{
|
||||
link: "https://google.com",
|
||||
type: OrganizerLinkOption.value,
|
||||
displayLocationPublicly: true,
|
||||
},
|
||||
];
|
||||
const { formMethods } = renderComponent({
|
||||
props: {
|
||||
fields: getBookingFieldsWithSystemFields({
|
||||
disableGuests: false,
|
||||
bookingFields: [],
|
||||
metadata: null,
|
||||
workflows: [],
|
||||
customInputs: [],
|
||||
}),
|
||||
locations,
|
||||
isDynamicGroupBooking: false,
|
||||
bookingData: null,
|
||||
},
|
||||
formDefaultValues: {},
|
||||
});
|
||||
|
||||
component.fillName({ value: "John Doe" });
|
||||
component.fillEmail({ value: "[email protected]" });
|
||||
component.fillNotes({ value: "This is a note" });
|
||||
expectScenarios.expectNameToBe({ value: "John Doe", formMethods });
|
||||
expectScenarios.expectEmailToBe({ value: "[email protected]", formMethods });
|
||||
expectScenarios.expectNotesToBe({ value: "This is a note", formMethods });
|
||||
|
||||
component.fillRadioInputLocation({ label: AttendeePhoneNumberOption.label, inputValue: "+1234567890" });
|
||||
expectScenarios.expectLocationToBe({
|
||||
formMethods,
|
||||
label: AttendeePhoneNumberOption.label,
|
||||
toMatch: {
|
||||
formattedValue: "+1 (234) 567-890",
|
||||
value: { optionValue: "+1234567890", value: AttendeePhoneNumberOption.value },
|
||||
},
|
||||
});
|
||||
|
||||
component.fillRadioInputLocation({ label: OrganizerLinkOption.label });
|
||||
expectScenarios.expectLocationToBe({
|
||||
formMethods,
|
||||
label: OrganizerLinkOption.label,
|
||||
toMatch: {
|
||||
formattedValue: "+1 (234) 567-890",
|
||||
value: { optionValue: "", value: OrganizerLinkOption.value },
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const component = {
|
||||
getName: ({ label = "your_name" }: { label?: string } = {}) =>
|
||||
screen.getByRole("textbox", {
|
||||
name: new RegExp(label),
|
||||
}) as HTMLInputElement,
|
||||
getEmail: () => screen.getByRole("textbox", { name: /email/i }) as HTMLInputElement,
|
||||
getLocationRadioOption: ({ label }: { label: string }) =>
|
||||
screen.getByRole("radio", { name: new RegExp(label) }) as HTMLInputElement,
|
||||
getLocationRadioInput: ({ placeholder }: { placeholder: string }) =>
|
||||
screen.getByPlaceholderText(placeholder) as HTMLInputElement,
|
||||
getNotes: () => screen.getByRole("textbox", { name: /additional_notes/i }) as HTMLInputElement,
|
||||
getGuests: () => screen.getByLabelText("guests"),
|
||||
fillName: ({ value }: { value: string }) => {
|
||||
fireEvent.change(component.getName(), { target: { value } });
|
||||
},
|
||||
fillEmail: ({ value }: { value: string }) => {
|
||||
fireEvent.change(component.getEmail(), { target: { value } });
|
||||
},
|
||||
fillRadioInputLocation: ({ label, inputValue }: { label: string; inputValue?: string }) => {
|
||||
fireEvent.click(component.getLocationRadioOption({ label }));
|
||||
|
||||
if (inputValue) {
|
||||
let placeholder = label;
|
||||
if (label === "attendee_phone_number") {
|
||||
placeholder = "enter_phone_number";
|
||||
} else {
|
||||
// radioInput doesn't have a label, so we need to identify by placeholder
|
||||
throw new Error("Tell me how to identify the placeholder for this location input");
|
||||
}
|
||||
fireEvent.change(component.getLocationRadioInput({ placeholder }), {
|
||||
target: { value: inputValue },
|
||||
});
|
||||
}
|
||||
},
|
||||
fillNotes: ({ value }: { value: string }) => {
|
||||
fireEvent.change(component.getNotes(), { target: { value } });
|
||||
},
|
||||
};
|
||||
|
||||
const expectScenarios = {
|
||||
expectNameToBe: ({ value, formMethods }: { value: string; formMethods: FormMethods }) => {
|
||||
expect(component.getName().value).toEqual(value);
|
||||
expect(formMethods.getValues("responses.name")).toEqual(value);
|
||||
},
|
||||
expectEmailToBe: ({ value, formMethods }: { value: string; formMethods: FormMethods }) => {
|
||||
expect(component.getEmail().value).toEqual(value);
|
||||
expect(formMethods.getValues("responses.email")).toEqual(value);
|
||||
},
|
||||
expectLocationToBe: ({
|
||||
formMethods,
|
||||
label,
|
||||
toMatch: { formattedValue, value },
|
||||
}: {
|
||||
label: string;
|
||||
toMatch: {
|
||||
formattedValue?: string;
|
||||
value: {
|
||||
optionValue: string;
|
||||
value: string;
|
||||
};
|
||||
};
|
||||
formMethods: FormMethods;
|
||||
}) => {
|
||||
expect(component.getLocationRadioOption({ label }).checked).toBe(true);
|
||||
if (value.optionValue) {
|
||||
expect(component.getLocationRadioInput({ placeholder: "enter_phone_number" }).value).toEqual(
|
||||
formattedValue
|
||||
);
|
||||
}
|
||||
expect(formMethods.getValues("responses.location")).toEqual(value);
|
||||
},
|
||||
expectNotesToBe: ({ value, formMethods }: { value: string; formMethods: FormMethods }) => {
|
||||
expect(component.getNotes().value).toEqual(value);
|
||||
expect(formMethods.getValues("responses.notes")).toEqual(value);
|
||||
},
|
||||
};
|
||||
@@ -83,11 +83,8 @@ export const BookingFields = ({
|
||||
return null;
|
||||
}
|
||||
|
||||
// Attendee location field can be edited during reschedule
|
||||
if (field.name === SystemField.Enum.location) {
|
||||
if (locationResponse?.value === "attendeeInPerson" || "phone") {
|
||||
readOnly = false;
|
||||
}
|
||||
readOnly = false;
|
||||
}
|
||||
|
||||
// Dynamically populate location field options
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
|
||||
type Fields = z.infer<typeof eventTypeBookingFields>;
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
if (typeof window !== "undefined" && !process.env.INTEGRATION_TEST_MODE) {
|
||||
// This file imports some costly dependencies, so we want to make sure it's not imported on the client side.
|
||||
throw new Error("`getBookingFields` must not be imported on the client side.");
|
||||
}
|
||||
|
||||
@@ -97,16 +97,16 @@ type Component =
|
||||
export const Components: Record<FieldType, Component> = {
|
||||
text: {
|
||||
propsType: propsTypes.text,
|
||||
factory: (props) => <Widgets.TextWidget noLabel={true} {...props} />,
|
||||
factory: (props) => <Widgets.TextWidget id={props.name} noLabel={true} {...props} />,
|
||||
},
|
||||
textarea: {
|
||||
propsType: propsTypes.textarea,
|
||||
// TODO: Make rows configurable in the form builder
|
||||
factory: (props) => <Widgets.TextAreaWidget rows={3} {...props} />,
|
||||
factory: (props) => <Widgets.TextAreaWidget id={props.name} rows={3} {...props} />,
|
||||
},
|
||||
number: {
|
||||
propsType: propsTypes.number,
|
||||
factory: (props) => <Widgets.NumberWidget noLabel={true} {...props} />,
|
||||
factory: (props) => <Widgets.NumberWidget id={props.name} noLabel={true} {...props} />,
|
||||
},
|
||||
name: {
|
||||
propsType: propsTypes.name,
|
||||
@@ -211,7 +211,7 @@ export const Components: Record<FieldType, Component> = {
|
||||
if (!props) {
|
||||
return <div />;
|
||||
}
|
||||
return <Widgets.TextWidget type="email" noLabel={true} {...props} />;
|
||||
return <Widgets.TextWidget type="email" id={props.name} noLabel={true} {...props} />;
|
||||
},
|
||||
},
|
||||
address: {
|
||||
@@ -219,6 +219,7 @@ export const Components: Record<FieldType, Component> = {
|
||||
factory: (props) => {
|
||||
return (
|
||||
<AddressInput
|
||||
id={props.name}
|
||||
onChange={(val) => {
|
||||
props.setValue(val);
|
||||
}}
|
||||
@@ -248,6 +249,7 @@ export const Components: Record<FieldType, Component> = {
|
||||
{value.map((field, index) => (
|
||||
<li key={index}>
|
||||
<EmailField
|
||||
id={`${props.name}.${index}`}
|
||||
disabled={readOnly}
|
||||
value={value[index]}
|
||||
className={inputClassName}
|
||||
@@ -319,7 +321,7 @@ export const Components: Record<FieldType, Component> = {
|
||||
...props,
|
||||
listValues: props.options.map((o) => ({ title: o.label, value: o.value })),
|
||||
};
|
||||
return <Widgets.MultiSelectWidget {...newProps} />;
|
||||
return <Widgets.MultiSelectWidget id={props.name} {...newProps} />;
|
||||
},
|
||||
},
|
||||
select: {
|
||||
@@ -329,7 +331,7 @@ export const Components: Record<FieldType, Component> = {
|
||||
...props,
|
||||
listValues: props.options.map((o) => ({ title: o.label, value: o.value })),
|
||||
};
|
||||
return <Widgets.SelectWidget {...newProps} />;
|
||||
return <Widgets.SelectWidget id={props.name} {...newProps} />;
|
||||
},
|
||||
},
|
||||
checkbox: {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { TooltipProvider } from "@radix-ui/react-tooltip";
|
||||
import { render } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { React } from "react";
|
||||
import * as React from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { vi } from "vitest";
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
setMockMatchMedia,
|
||||
pageObject,
|
||||
expectScenario,
|
||||
getLocationBookingField,
|
||||
} from "./testUtils";
|
||||
|
||||
vi.mock("@formkit/auto-animate/react", () => ({
|
||||
@@ -115,43 +116,23 @@ describe("FormBuilder", () => {
|
||||
},
|
||||
},
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
shouldConsiderRequired: ({ field: any }) => {
|
||||
field.name === "location" ? true : false;
|
||||
// @typescript-eslint/no-explicit-any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
shouldConsiderRequired: (field: any) => {
|
||||
return field.name === "location" ? true : false;
|
||||
},
|
||||
},
|
||||
// TODO: May be we should get this from getBookingFields directly which tests more practical cases
|
||||
formDefaultValues: {
|
||||
fields: [
|
||||
{
|
||||
defaultLabel: "location",
|
||||
type: field.type,
|
||||
name: field.identifier,
|
||||
editable: "system",
|
||||
hideWhenJustOneOption: true,
|
||||
required: false,
|
||||
getOptionsAt: "locations",
|
||||
optionsInputs: {
|
||||
attendeeInPerson: {
|
||||
type: "address",
|
||||
required: true,
|
||||
placeholder: "",
|
||||
},
|
||||
phone: {
|
||||
type: "phone",
|
||||
required: true,
|
||||
placeholder: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
fields: [getLocationBookingField()],
|
||||
},
|
||||
});
|
||||
|
||||
// editable:'system' field can't be deleted
|
||||
expect(pageObject.queryDeleteButton({ identifier: field.identifier })).toBeNull();
|
||||
expectScenario.toNotHaveDeleteButton({ identifier: field.identifier });
|
||||
// editable:'system' field can't be toggled
|
||||
expect(pageObject.queryToggleButton({ identifier: field.identifier })).toBeNull();
|
||||
expectScenario.toNotHaveToggleButton({ identifier: field.identifier });
|
||||
expectScenario.toHaveSourceBadge({ identifier: field.identifier, sourceLabel: "1 Location" });
|
||||
expectScenario.toHaveRequiredBadge({ identifier: field.identifier });
|
||||
|
||||
const newFieldDialog = pageObject.openAddFieldDialog();
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import * as React from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { FormBuilderField } from "./FormBuilderField";
|
||||
|
||||
vi.mock("@formkit/auto-animate/react", () => ({
|
||||
useAutoAnimate: () => [null],
|
||||
}));
|
||||
|
||||
const renderComponent = ({
|
||||
props: props,
|
||||
formDefaultValues,
|
||||
}: {
|
||||
props: Parameters<typeof FormBuilderField>[0];
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
formDefaultValues?: any;
|
||||
}) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let formMethods: UseFormReturn<any> | undefined;
|
||||
const Wrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
const form = useForm({
|
||||
defaultValues: formDefaultValues,
|
||||
});
|
||||
formMethods = form;
|
||||
return <FormProvider {...form}>{children}</FormProvider>;
|
||||
};
|
||||
render(<FormBuilderField {...props} />, { wrapper: Wrapper });
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return { formMethods: formMethods! };
|
||||
};
|
||||
|
||||
describe("FormBuilderField", () => {
|
||||
it("verify a text type input field", () => {
|
||||
const { formMethods } = renderComponent({
|
||||
props: {
|
||||
field: {
|
||||
name: "textInput1",
|
||||
type: "text",
|
||||
label: "Text Input 1",
|
||||
placeholder: "Enter text",
|
||||
},
|
||||
readOnly: false,
|
||||
className: "",
|
||||
},
|
||||
formDefaultValues: {},
|
||||
});
|
||||
expect(component.getFieldInput({ label: "Text Input 1" }).value).toEqual("");
|
||||
component.fillFieldInput({ label: "Text Input 1", value: "test" });
|
||||
expectScenario.toHaveFieldValue({
|
||||
label: "Text Input 1",
|
||||
identifier: "textInput1",
|
||||
value: "test",
|
||||
formMethods,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const component = {
|
||||
getFieldInput: ({ label }) => screen.getByRole("textbox", { name: label }) as HTMLInputElement,
|
||||
fillFieldInput: ({ label, value }: { label: string; value: string }) => {
|
||||
fireEvent.change(component.getFieldInput({ label }), { target: { value } });
|
||||
},
|
||||
};
|
||||
|
||||
const expectScenario = {
|
||||
toHaveFieldValue: ({
|
||||
identifier,
|
||||
label,
|
||||
value,
|
||||
formMethods,
|
||||
}: {
|
||||
identifier: string;
|
||||
label: string;
|
||||
value: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
formMethods: UseFormReturn<any>;
|
||||
}) => {
|
||||
expect(component.getFieldInput({ label }).value).toEqual(value);
|
||||
expect(formMethods.getValues(`responses.${identifier}`)).toEqual(value);
|
||||
},
|
||||
};
|
||||
@@ -130,12 +130,14 @@ const WithLabel = ({
|
||||
field,
|
||||
children,
|
||||
readOnly,
|
||||
htmlFor,
|
||||
noLabel = false,
|
||||
}: {
|
||||
field: Partial<RhfFormField>;
|
||||
readOnly: boolean;
|
||||
children: React.ReactNode;
|
||||
noLabel?: boolean;
|
||||
htmlFor: string;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
@@ -150,7 +152,7 @@ const WithLabel = ({
|
||||
field.type !== "multiemail" &&
|
||||
field.label && (
|
||||
<div className="mb-2 flex items-center">
|
||||
<Label className="!mb-0 flex">
|
||||
<Label className="!mb-0 flex" htmlFor={htmlFor}>
|
||||
<span>{field.label}</span>
|
||||
<span className="text-emphasis -mb-1 ml-1 text-sm font-medium leading-none">
|
||||
{!readOnly && field.required ? "*" : ""}
|
||||
@@ -249,7 +251,7 @@ export const ComponentForField = ({
|
||||
}
|
||||
if (componentConfig.propsType === "text") {
|
||||
return (
|
||||
<WithLabel field={field} readOnly={readOnly} noLabel={noLabel}>
|
||||
<WithLabel field={field} htmlFor={field.name} readOnly={readOnly} noLabel={noLabel}>
|
||||
<componentConfig.factory
|
||||
placeholder={field.placeholder}
|
||||
minLength={field.minLength}
|
||||
@@ -266,7 +268,7 @@ export const ComponentForField = ({
|
||||
|
||||
if (componentConfig.propsType === "boolean") {
|
||||
return (
|
||||
<WithLabel field={field} readOnly={readOnly} noLabel={noLabel}>
|
||||
<WithLabel field={field} htmlFor={field.name} readOnly={readOnly} noLabel={noLabel}>
|
||||
<componentConfig.factory
|
||||
name={field.name}
|
||||
label={field.label}
|
||||
@@ -281,7 +283,7 @@ export const ComponentForField = ({
|
||||
|
||||
if (componentConfig.propsType === "textList") {
|
||||
return (
|
||||
<WithLabel field={field} readOnly={readOnly} noLabel={noLabel}>
|
||||
<WithLabel field={field} htmlFor={field.name} readOnly={readOnly} noLabel={noLabel}>
|
||||
<componentConfig.factory
|
||||
placeholder={field.placeholder}
|
||||
name={field.name}
|
||||
@@ -300,7 +302,7 @@ export const ComponentForField = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<WithLabel field={field} readOnly={readOnly} noLabel={noLabel}>
|
||||
<WithLabel field={field} htmlFor={field.name} readOnly={readOnly} noLabel={noLabel}>
|
||||
<componentConfig.factory
|
||||
readOnly={readOnly}
|
||||
value={value as string}
|
||||
@@ -318,7 +320,7 @@ export const ComponentForField = ({
|
||||
throw new Error("Field options is not defined");
|
||||
}
|
||||
return (
|
||||
<WithLabel field={field} readOnly={readOnly} noLabel={noLabel}>
|
||||
<WithLabel field={field} htmlFor={field.name} readOnly={readOnly} noLabel={noLabel}>
|
||||
<componentConfig.factory
|
||||
placeholder={field.placeholder}
|
||||
name={field.name}
|
||||
@@ -342,7 +344,7 @@ export const ComponentForField = ({
|
||||
const options = field.options;
|
||||
|
||||
return field.options.length ? (
|
||||
<WithLabel field={field} readOnly={readOnly} noLabel={noLabel}>
|
||||
<WithLabel field={field} htmlFor={field.name} readOnly={readOnly} noLabel={noLabel}>
|
||||
<componentConfig.factory
|
||||
placeholder={field.placeholder}
|
||||
readOnly={readOnly}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { TooltipProvider } from "@radix-ui/react-tooltip";
|
||||
import { render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { FormBuilder } from "@calcom/features/form-builder/FormBuilder";
|
||||
|
||||
import { mockProps, questionUtils, setMockIntersectionObserver, setMockMatchMedia } from "./testUtils";
|
||||
|
||||
vi.mock("@formkit/auto-animate/react", () => ({
|
||||
useAutoAnimate: () => [null],
|
||||
}));
|
||||
|
||||
const renderComponent = () => {
|
||||
const Wrapper = ({ children }: { children: ReactNode }) => {
|
||||
const methods = useForm();
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<FormProvider {...methods}>{children}</FormProvider>
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
|
||||
return render(<FormBuilder {...mockProps} />, { wrapper: Wrapper });
|
||||
};
|
||||
|
||||
const questionTypes = [
|
||||
{ questionType: "email", label: "Email Field" },
|
||||
{ questionType: "phone", label: "Phone Field" },
|
||||
{ questionType: "address", label: "Address Field" },
|
||||
{ questionType: "text", label: "Short Text Field" },
|
||||
{ questionType: "number", label: "Number Field" },
|
||||
{ questionType: "textarea", label: "Long Text Field" },
|
||||
{ questionType: "select", label: "Select Field" },
|
||||
{ questionType: "multiselect", label: "MultiSelect Field" },
|
||||
{ questionType: "multiemail", label: "Multiple Emails Field" },
|
||||
{ questionType: "checkbox", label: "CheckBox Group Field" },
|
||||
{ questionType: "radio", label: "Radio Group Field" },
|
||||
{ questionType: "boolean", label: "Checkbox Field" },
|
||||
];
|
||||
|
||||
describe("Form Builder - Add and Edit", () => {
|
||||
beforeAll(() => {
|
||||
setMockMatchMedia();
|
||||
setMockIntersectionObserver();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
renderComponent();
|
||||
});
|
||||
|
||||
for (const { questionType, label } of questionTypes) {
|
||||
it(`should successfully create or edit a ${label} question type in the form builder, with the option to disable the field on prefill`, async () => {
|
||||
const defaultIdentifier = `${questionType}-id`;
|
||||
const newIdentifier = `${defaultIdentifier}-edited`;
|
||||
|
||||
// Add a question
|
||||
await questionUtils.addQuestion({
|
||||
questionType,
|
||||
identifier: defaultIdentifier,
|
||||
label,
|
||||
disableOnPrefill: true,
|
||||
});
|
||||
questionUtils.expectedValueForDisablePreFillCheckox(true);
|
||||
|
||||
// Edit the question
|
||||
await questionUtils.editQuestion({
|
||||
identifier: newIdentifier,
|
||||
existingQuestionId: defaultIdentifier,
|
||||
disableOnPrefill: false,
|
||||
});
|
||||
questionUtils.expectedValueForDisablePreFillCheckox(false);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,184 +0,0 @@
|
||||
import { fireEvent, waitFor, screen } from "@testing-library/react";
|
||||
import { vi } from "vitest";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { fieldsSchema } from "@calcom/features/form-builder/schema";
|
||||
|
||||
type RhfForm = {
|
||||
fields: z.infer<typeof fieldsSchema>;
|
||||
};
|
||||
|
||||
type RhfFormFields = RhfForm["fields"];
|
||||
|
||||
export type RhfFormField = RhfFormFields[number];
|
||||
|
||||
export type FieldType = RhfFormField["type"];
|
||||
export interface QuestionProps {
|
||||
questionType: string;
|
||||
identifier: string;
|
||||
label: string;
|
||||
disableOnPrefill?: boolean;
|
||||
}
|
||||
|
||||
export interface FormBuilderProps {
|
||||
formProp: string;
|
||||
title: string;
|
||||
description: string;
|
||||
addFieldLabel: string;
|
||||
disabled: boolean;
|
||||
LockedIcon: false | JSX.Element;
|
||||
dataStore: {
|
||||
options: Record<string, { label: string; value: string; inputPlaceholder?: string }[]>;
|
||||
};
|
||||
disableOnPrefill?: boolean;
|
||||
}
|
||||
|
||||
export interface FormBuildFieldProps {
|
||||
field: Omit<RhfFormField, "editable" | "label"> & {
|
||||
// Label is optional because radioInput doesn't have a label
|
||||
label?: string;
|
||||
value: string;
|
||||
};
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
export const mockProps: FormBuilderProps = {
|
||||
formProp: "formProp",
|
||||
title: "FormBuilder Title",
|
||||
description: "FormBuilder Description",
|
||||
addFieldLabel: "Add Field",
|
||||
disabled: false,
|
||||
LockedIcon: false,
|
||||
dataStore: { options: {} },
|
||||
disableOnPrefill: false,
|
||||
};
|
||||
|
||||
export const mockFieldProps: FormBuildFieldProps = {
|
||||
field: {
|
||||
type: "text",
|
||||
name: "test-text-n",
|
||||
variant: "text",
|
||||
placeholder: "text-test-p",
|
||||
required: false,
|
||||
label: "text-test-l",
|
||||
disableOnPrefill: false,
|
||||
value: "",
|
||||
},
|
||||
readOnly: false,
|
||||
};
|
||||
|
||||
export const setMockMatchMedia = () => {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
value: vi.fn().mockImplementation((query) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
};
|
||||
|
||||
export const setMockIntersectionObserver = () => {
|
||||
Object.defineProperty(window, "IntersectionObserver", {
|
||||
value: vi.fn().mockImplementation(() => ({
|
||||
observe: vi.fn(),
|
||||
unobserve: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
takeRecords: vi.fn(() => []),
|
||||
})),
|
||||
});
|
||||
};
|
||||
|
||||
export const clickDisablePrefillBasedOnUserInput = (disableOnPrefill?: boolean) => {
|
||||
if (typeof disableOnPrefill === "boolean") {
|
||||
// Get the checkbox element
|
||||
const checkbox = getDisablePrefillCheckbox(disableOnPrefill) as HTMLInputElement;
|
||||
|
||||
// Determine if the checkbox's current state differs from the `disableOnPrefill` prop
|
||||
const isChecked = checkbox ? checkbox.checked : false;
|
||||
|
||||
// Click the checkbox only if its current state differs from the `disableOnPrefill` value
|
||||
if (isChecked !== disableOnPrefill) {
|
||||
fireEvent.click(checkbox);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const getDisablePrefillCheckbox = (disableOnPrefill?: boolean) => {
|
||||
if (typeof disableOnPrefill === "boolean") {
|
||||
const checkbox = screen.getByRole("checkbox", { name: /disable_input_if_prefilled/i });
|
||||
return checkbox;
|
||||
}
|
||||
};
|
||||
|
||||
export const checkForDisablePreFillCheckox = (disableOnPrefill?: boolean) => {
|
||||
const checkbox = getDisablePrefillCheckbox(disableOnPrefill);
|
||||
expect(checkbox).toBeInTheDocument();
|
||||
};
|
||||
|
||||
export const questionUtils = {
|
||||
addQuestion: async (props: QuestionProps) => {
|
||||
fireEvent.click(screen.getByTestId("add-field"));
|
||||
checkForDisablePreFillCheckox(props?.disableOnPrefill);
|
||||
fireEvent.keyDown(screen.getByTestId("test-field-type"), { key: "ArrowDown", code: "ArrowDown" });
|
||||
fireEvent.click(screen.getByTestId(`select-option-${props.questionType}`));
|
||||
fireEvent.change(screen.getAllByRole("textbox")[0], { target: { value: props.identifier } });
|
||||
fireEvent.change(screen.getAllByRole("textbox")[1], { target: { value: props.label } });
|
||||
clickDisablePrefillBasedOnUserInput(props?.disableOnPrefill);
|
||||
fireEvent.click(screen.getByTestId("field-add-save"));
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId(`field-${props.identifier}`)).toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
editQuestion: async (props: {
|
||||
identifier: string;
|
||||
existingQuestionId: string;
|
||||
disableOnPrefill?: boolean;
|
||||
}) => {
|
||||
fireEvent.click(screen.getByTestId("edit-field-action"));
|
||||
checkForDisablePreFillCheckox(props?.disableOnPrefill);
|
||||
fireEvent.change(screen.getAllByRole("textbox")[0], { target: { value: props.identifier } });
|
||||
clickDisablePrefillBasedOnUserInput(props?.disableOnPrefill);
|
||||
|
||||
fireEvent.click(screen.getByTestId("field-add-save"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId(`field-${props.identifier}`)).toBeInTheDocument();
|
||||
expect(screen.queryByTestId(`field-${props.existingQuestionId}`)).not.toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
deleteQuestion: async (existingQuestionId: string) => {
|
||||
expect(screen.queryByTestId(`field-${existingQuestionId}`)).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByTestId("delete-field-action"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId(`field-${existingQuestionId}`)).not.toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
hideQuestion: async () => {
|
||||
fireEvent.click(screen.getByTestId("toggle-field"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText(/hidden/i)).toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
requiredAndOptionalQuestion: async () => {
|
||||
expect(screen.queryByTestId("required")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByTestId("edit-field-action"));
|
||||
fireEvent.click(screen.getAllByRole("radio")[1]);
|
||||
fireEvent.click(screen.getByTestId("field-add-save"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("optional")).toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
expectedValueForDisablePreFillCheckox: async (expectedValue: boolean) => {
|
||||
fireEvent.click(screen.getByTestId("edit-field-action"));
|
||||
const checkbox = getDisablePrefillCheckbox(expectedValue) as HTMLInputElement;
|
||||
await expect(checkbox?.checked).toBe(expectedValue);
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,8 @@
|
||||
import { fireEvent, waitFor, screen, within } from "@testing-library/react";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
|
||||
|
||||
import type { FormBuilder } from "./FormBuilder";
|
||||
|
||||
export interface FieldProps {
|
||||
@@ -20,6 +22,22 @@ export const mockProps: FormBuilderProps = {
|
||||
LockedIcon: false,
|
||||
dataStore: { options: {} },
|
||||
};
|
||||
export const getLocationBookingField = () => {
|
||||
const bookingFields = getBookingFieldsWithSystemFields({
|
||||
bookingFields: [],
|
||||
disableGuests: false,
|
||||
disableBookingTitle: false,
|
||||
customInputs: [],
|
||||
metadata: {},
|
||||
workflows: [],
|
||||
});
|
||||
|
||||
const locationBookingField = bookingFields.find((field) => field.name === "location");
|
||||
if (!locationBookingField) {
|
||||
throw new Error("location booking field not found");
|
||||
}
|
||||
return locationBookingField;
|
||||
};
|
||||
|
||||
export const setMockMatchMedia = () => {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
@@ -197,8 +215,7 @@ export const verifier = {
|
||||
});
|
||||
},
|
||||
verifyThatFieldCanBeMarkedOptional: async ({ identifier }: { identifier: string }) => {
|
||||
const field = getFieldInTheList({ identifier });
|
||||
expect(field.getByTestId("required")).toBeInTheDocument();
|
||||
expectScenario.toHaveRequiredBadge({ identifier });
|
||||
const editDialogForm = pageObject.openEditFieldDialog({ identifier });
|
||||
pageObject.dialog.makeFieldOptional({ dialog: editDialogForm });
|
||||
pageObject.dialog.saveField({ dialog: editDialogForm });
|
||||
@@ -222,8 +239,8 @@ export const expectScenario = {
|
||||
expect(identifierInput.disabled).toBe(true);
|
||||
},
|
||||
toHaveRequirablityToggleDisabled: ({ dialog }: { dialog: TestingLibraryElement }) => {
|
||||
const no = within(dialog.getByTestId("field-required")).getByText("No");
|
||||
const yes = within(dialog.getByTestId("field-required")).getByText("Yes");
|
||||
const no = within(dialog.getByTestId("field-required")).getByText("No") as HTMLButtonElement;
|
||||
const yes = within(dialog.getByTestId("field-required")).getByText("Yes") as HTMLButtonElement;
|
||||
expect(no.disabled).toBe(true);
|
||||
expect(yes.disabled).toBe(true);
|
||||
},
|
||||
@@ -231,4 +248,18 @@ export const expectScenario = {
|
||||
const labelInput = dialog.getByLabelText("label");
|
||||
expect(labelInput.disabled).toBe(false);
|
||||
},
|
||||
toNotHaveDeleteButton: ({ identifier }: { identifier: string }) => {
|
||||
expect(pageObject.queryDeleteButton({ identifier })).toBeNull();
|
||||
},
|
||||
toNotHaveToggleButton: ({ identifier }: { identifier: string }) => {
|
||||
expect(pageObject.queryToggleButton({ identifier })).toBeNull();
|
||||
},
|
||||
toHaveSourceBadge: ({ identifier, sourceLabel }: { identifier: string; sourceLabel: string }) => {
|
||||
const field = getFieldInTheList({ identifier });
|
||||
expect(field.getByText(sourceLabel)).not.toBeNull();
|
||||
},
|
||||
toHaveRequiredBadge: ({ identifier }: { identifier: string }) => {
|
||||
const field = getFieldInTheList({ identifier });
|
||||
expect(field.getByText("required")).not.toBeNull();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { vi } from "vitest";
|
||||
|
||||
vi.mock("@calcom/ui", async (originalImport) => {
|
||||
const original = (await originalImport()) as Record<string, unknown>;
|
||||
// Dynamic imports of Components are not supported in Vitest. So, we use the non-lazy version of the components
|
||||
return {
|
||||
...original,
|
||||
PhoneInput: original.PhoneInputNonLazy,
|
||||
AddressInput: original.AddressInputNonLazy,
|
||||
};
|
||||
});
|
||||
|
||||
export {};
|
||||
@@ -85,6 +85,7 @@ export const InputField = forwardRef<HTMLInputElement, InputFieldProps>(function
|
||||
type,
|
||||
hintErrors,
|
||||
labelSrOnly,
|
||||
noLabel,
|
||||
containerClassName,
|
||||
readOnly,
|
||||
showAsteriskIndicator,
|
||||
@@ -99,7 +100,7 @@ export const InputField = forwardRef<HTMLInputElement, InputFieldProps>(function
|
||||
|
||||
return (
|
||||
<div className={classNames(containerClassName)}>
|
||||
{!!name && (
|
||||
{!!name && !noLabel && (
|
||||
<Skeleton
|
||||
as={Label}
|
||||
htmlFor={id}
|
||||
|
||||
@@ -18,6 +18,7 @@ export type InputFieldProps = {
|
||||
showAsteriskIndicator?: boolean;
|
||||
t?: (key: string) => string;
|
||||
dataTestid?: string;
|
||||
noLabel?: boolean;
|
||||
onClickAddon?: () => void;
|
||||
} & React.ComponentProps<typeof Input> & {
|
||||
labelProps?: React.ComponentProps<typeof Label>;
|
||||
|
||||
@@ -151,6 +151,9 @@ export { ShellSubHeading } from "./components/layout";
|
||||
export { default as AddressInput } from "./form/AddressInputLazy";
|
||||
export { default as PhoneInput } from "./form/PhoneInputLazy";
|
||||
export { default as MultiEmail } from "./form/MultiEmailLazy";
|
||||
export { default as PhoneInputNonLazy } from "./form/PhoneInput";
|
||||
export { default as AddressInputNonLazy } from "./form/AddressInput";
|
||||
|
||||
export { UnstyledSelect } from "./form/Select";
|
||||
|
||||
export {
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
"./components/icon/SatSymbol": "./components/icon/SatSymbol.tsx",
|
||||
"./components/icon/Spinner": "./components/icon/Spinner.tsx",
|
||||
"./components/unpublished-entity/UnpublishedEntity": "./components/unpublished-entity/index.ts",
|
||||
"./components/form/timezone-select/TimezoneSelect": "./components/form/timezone-select/index.ts"
|
||||
"./components/form/timezone-select/TimezoneSelect": "./components/form/timezone-select/index.ts",
|
||||
"./__mocks__/ui": "./__mocks__/ui.tsx"
|
||||
},
|
||||
"types": "./index.tsx",
|
||||
"license": "MIT",
|
||||
|
||||
+11
-2
@@ -107,7 +107,7 @@ const workspaces = packagedEmbedTestsOnly
|
||||
globals: true,
|
||||
name: "@calcom/features",
|
||||
include: ["packages/features/**/*.{test,spec}.tsx"],
|
||||
exclude: ["packages/features/form-builder/**/*"],
|
||||
exclude: ["packages/features/form-builder/**/*", "packages/features/bookings/**/*"],
|
||||
environment: "jsdom",
|
||||
setupFiles: ["setupVitest.ts", "packages/ui/components/test-setup.ts"],
|
||||
},
|
||||
@@ -154,7 +154,16 @@ const workspaces = packagedEmbedTestsOnly
|
||||
test: {
|
||||
globals: true,
|
||||
name: "@calcom/features/form-builder",
|
||||
include: ["packages/features/form-builder/**/*.{test,spec}.[jt]s?(x)"],
|
||||
include: ["packages/features/form-builder/**/*.{test,spec}.[jt]sx"],
|
||||
environment: "jsdom",
|
||||
setupFiles: ["packages/ui/components/test-setup.ts"],
|
||||
},
|
||||
},
|
||||
{
|
||||
test: {
|
||||
globals: true,
|
||||
name: "@calcom/features/bookings",
|
||||
include: ["packages/features/bookings/**/*.{test,spec}.[jt]sx"],
|
||||
environment: "jsdom",
|
||||
setupFiles: ["packages/ui/components/test-setup.ts"],
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user