import React from "react";
import { fireEvent, render } from "@testing-library/react";

import { NumberField } from "./index";

describe("NumberField", () => {
  it("renders with form label and aria describe", () => {
    const { getByText } = render(
      <NumberField
        name="My First Field"
        description="Some helper text"
      />
    );

    const labelEl = getByText("My First Field");
    const describeEl = getByText("Some helper text");

    expect(labelEl.htmlFor).toEqual("number-field-my-first-field");
    expect(describeEl.id).toEqual("number-field-my-first-field-describe");
  });

  it("input is of type number", () => {
    const { getByLabelText } = render(
      <NumberField
        name="My First Field"
        description="Some helper text"
      />
    );

    const inputEl = getByLabelText("My First Field", { selector: "input" });

    expect(inputEl.type).toEqual("number");
  });

  it("updates parent state", () => {
    let mockState = 0;
    const mockSetState = jest.fn((value) => mockState = value);

    const { getByLabelText } = render(
      <NumberField
        name="My First Field"
        description="Enter a number"
        value={mockState}
        setValue={mockSetState}
      />
    );

    const inputEl = getByLabelText("My First Field", { selector: "input" });

    fireEvent.change(inputEl, { target: { value: "1" } });

    expect(mockState).toEqual("1");
    expect(mockSetState.mock.calls.length).toEqual(1);
  });
})