import { fireEvent, render, waitFor } from "@testing-library/react";
import { ContextScope } from "@reins/utils";

import { FormAdapter } from "utils";
import { Form } from "../form";

describe("Form [ Base ]", () => {
  const initialValues = {
    name: "name",
    email: "email",
    password: "password",
  };
  const form = new FormAdapter(initialValues);
  const formContexts = new ContextScope("Form").createContext("FormProvider", { form });

  const [FormProvider] = formContexts.getContext("FormProvider");

  const Provider = (props: Omit<Parameters<typeof FormProvider.Provider>[0], "__context">) => (
    <FormProvider.Provider {...props} __context={formContexts} />
  );
  const onSubmit = jest.fn();

  beforeEach(() => {
    form.reset();
    onSubmit.mockClear();
  });
  it("should render and submit Form component", async () => {
    const { getByTestId } = render(
      <Form formAdapter={form} Provider={Provider} onSubmit={onSubmit}>
        <button data-testid="submit" type="submit">
          Submit
        </button>
      </Form>,
    );
    const submit = getByTestId("submit");
    fireEvent.click(submit);
    await waitFor(() => {
      expect(onSubmit).toHaveBeenCalledTimes(1);
      expect(onSubmit).toHaveBeenCalledWith(initialValues);
    });
  });
});
