nextui/packages/components/checkbox/__tests__/checkbox-group.test.tsx
WK 4e41f50fa2
v2.7.10 (#5381)
* fix(date-picker): error state (#5317)

* fix(date-range-picker): fixed the error state in preset

* Update giant-sloths-shop.md

* Removed if statement

* chore(date-picker): prettier

---------

Co-authored-by: WK Wong <wingkwong.code@gmail.com>

* fix(theme): clear button in mobile (#5252)

* fix(toast): fixed close button hover position

* fix(input): fixed the clear button rendering on smaller devices

* Delete .changeset/soft-spoons-march.md

* Update input.ts

* Undo unrelated toast changes

* fix(toast): icons (#5246)

* feat(shared-icons): add loading icon

* fix(toast): icons

* chore(toast): revise types for icons

* chore(changeset): add changeset

* refactor: migrate eslint to v9 (#5267)

* refactor: migrate eslint to v9

* chore: lint

* chore: update eslint command

* chore: fix lint warnings

* chore: separate lint and lint:fix

* chore: exclude contentlayer generated code

* fix(scripts): add missing await

* fix(autocomplete): persist last selected item position (#5286)

* refactor(select): remove unnecessary code

* fix(autocomplete): persist last selected item position

* chore(changeset): add changeset

* chore(deps): bump framer-motion version (#5287)

* chore(deps): bump framer-motion version

* fix: typing issues

* chore(changeset): add changeset

---------

Co-authored-by: Junior Garcia <jrgarciadev@gmail.com>

* chore(docs): supplement onAction & selectionBehavior (#5289)

* fix(autocomplete): ensure focused item matches selected item after filter, selection (#5290)

* fix(autocomplete): ensure focused item matches selected item after filter, selection

* chore: apply type and default value

* chore: add perpose coment in updated code

* test: add focuskey management testcode

* docs: add changeset

* docs: update changeset

* chore: remove comment

* fix: broken components in stories (#5291)

* chore(switch): remove xl size

* chore(docs): remove xl size

* chore(system-rsc): remove xl size

* chore(circular-progress): remove xl size

* chore: undo

* chore(deps): bump RA versions (#5310)

* chore(deps): ra version bump

* chore(changeset): add changeset

* fix(scripts): incorrect docs path

---------

Co-authored-by: Junior Garcia <jrgarciadev@gmail.com>

* chore(docs): update meta data (#5311)

* docs(layout.tsx): added text-foreground (#5316)

* feat(tabs): add click handling for tab items in tests and implementation (#3917)

Co-authored-by: WK Wong <wingkwong.code@gmail.com>

* fix issues in tabs examples (#2405)

Co-authored-by: WK Wong <wingkwong.code@gmail.com>

* chore(docs): add missing onValueChange in CheckboxGroup (#5332)

* ci(changesets): version packages (#5323)

Co-authored-by: Junior Garcia <jrgarciadev@gmail.com>

* chore(deps): bump RA versions (#5361)

* chore(deps): bump RA versions

* chore(deps): bump RA versions

* chore(deps): bump RA versions

* chore: changeset

* refactor(listbox): already extends in AriaListBoxProps

* chore(docs): remove herohack announcement (#5363)

* chore: remove herohack announcement

* Update carbon-ad.tsx

* chore(docs): fixed lint errors

* chore(docs): requested changes

* Update carbon-ad.tsx

* Update carbon-ad.tsx

* fix(theme): consistent faded styling for isInvalid in InputOtp and DateInput (#5349)

* fix(input-otp): remove bg and border styles from faded variant when isInvalid

* fix(date-input): remove bg styles from faded variant when isInvalid

* chore(changeset): add changeset

* chore: bump theme peerDependencies

* chore: bump theme peerDependencies

* fix: wrong version

* chore: extra line

---------

Co-authored-by: WK Wong <wingkwong.code@gmail.com>

* fix(theme): helperWrapper padding (#5350)

* fix(number-input): decreased helperWrapper padding to maintain consistency

* Update beige-laws-heal.md

* chore(theme): change to p-1

* chore(deps): bump peerDependencies for theme pkg

* fix(number-input): incorrect versions

* chore(changeset): include number input

---------

Co-authored-by: WK Wong <wingkwong.code@gmail.com>

* fix(autocomplete): onClear (#5365)

* fix(autocomplete): add onClear

* feat(autocomplete): add test case for onClear

* chore(changeset): add changeset

* fix(number-input): only allow number type (#5368)

* refactor(number-input): avoid non number type passing to number input

* chore(changeset): add changeset

* refactor: optimization (#5362)

* chore(deps): bump RA versions

* chore(deps): bump RA versions

* chore(deps): bump RA versions

* chore: changeset

* chore(deps): remove unnecessary dependencies

* fix(calendar): typing issue

* refactor(system): remove unused SupportedCalendars

* refactor(system): move I18nProviderProps to type

* refactor: use `spectrumCalendarProps<DateValue>["createCalendar"]`

* feat: add consistent-type-imports

* fix: eslint

* chore: add changeset

* refactor: remove unused deps

* ci(changesets): version packages (#5364)

Co-authored-by: Junior Garcia <jrgarciadev@gmail.com>

---------

Co-authored-by: Vishv Salvi <82429084+Vishvsalvi@users.noreply.github.com>
Co-authored-by: Junior Garcia <jrgarciadev@gmail.com>
Co-authored-by: KumJungMin <37934668+KumJungMin@users.noreply.github.com>
Co-authored-by: liaoyinglong <vigossliao@gmail.com>
Co-authored-by: zhengjitf <zhengjitf@gmail.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Anuj Kuralkar <76731106+anuj-kuralkar@users.noreply.github.com>
2025-06-16 11:28:11 -03:00

408 lines
14 KiB
TypeScript

import type {UserEvent} from "@testing-library/user-event";
import * as React from "react";
import {act, render} from "@testing-library/react";
import {Form} from "@heroui/form";
import userEvent from "@testing-library/user-event";
import {CheckboxGroup, Checkbox} from "../src";
describe("Checkbox.Group", () => {
let user: UserEvent;
beforeEach(() => {
user = userEvent.setup();
});
it("should render correctly", () => {
const wrapper = render(
<CheckboxGroup defaultValue={[]} label="Select cities">
<Checkbox value="sydney">Sydney</Checkbox>
<Checkbox value="buenos-aires">Buenos Aires</Checkbox>
</CheckboxGroup>,
);
expect(() => wrapper.unmount()).not.toThrow();
});
it("ref should be forwarded", () => {
const ref = React.createRef<HTMLDivElement>();
render(
<CheckboxGroup ref={ref} defaultValue={[]} label="Select cities">
<Checkbox value="sydney">Sydney</Checkbox>
<Checkbox value="buenos-aires">Buenos Aires</Checkbox>
</CheckboxGroup>,
);
expect(ref.current).not.toBeNull();
});
it("should work correctly with initial value", () => {
const {container} = render(
<CheckboxGroup defaultValue={["sydney"]} label="Select cities">
<Checkbox data-testid="first-checkbox" value="sydney">
Sydney
</Checkbox>
<Checkbox data-testid="second-checkbox" value="buenos-aires">
Buenos Aires
</Checkbox>
</CheckboxGroup>,
);
// check if the first checkbox is checked
expect(container.querySelector("[data-testid=first-checkbox] input")).toBeChecked();
// second checkbox should not be checked
expect(container.querySelector("[data-testid=second-checkbox] input")).not.toBeChecked();
});
it("should change value after click", async () => {
let value = ["sydney"];
const wrapper = render(
<CheckboxGroup
defaultValue={["sydney"]}
label="Select cities"
onChange={(val) => act(() => (value = val as string[]))}
>
<Checkbox data-testid="first-checkbox" value="sydney">
Sydney
</Checkbox>
<Checkbox data-testid="second-checkbox" value="buenos-aires">
Buenos Aires
</Checkbox>
</CheckboxGroup>,
);
const secondCheckbox = wrapper.getByTestId("second-checkbox");
await user.click(secondCheckbox);
expect(value).toEqual(["sydney", "buenos-aires"]);
});
it("should ignore events when disabled", () => {
const {container} = render(
<CheckboxGroup isDisabled defaultValue={["sydney"]} label="Select cities">
<Checkbox data-testid="first-checkbox" value="sydney">
Sydney
</Checkbox>
<Checkbox data-testid="second-checkbox" value="buenos-aires">
Buenos Aires
</Checkbox>
</CheckboxGroup>,
);
const firstCheckbox = container.querySelector("[data-testid=first-checkbox] input");
const secondCheckbox = container.querySelector("[data-testid=second-checkbox] input");
expect(firstCheckbox).toBeChecked();
expect(secondCheckbox).not.toBeChecked();
secondCheckbox && userEvent.click(secondCheckbox);
expect(firstCheckbox).toBeChecked();
expect(secondCheckbox).not.toBeChecked();
});
it("should work correctly with controlled value", async () => {
let checked = ["sydney"];
const onChange = jest.fn((value) => {
checked = value;
});
const wrapper = render(
<CheckboxGroup
label="Select cities"
value={checked}
onChange={(checked) => {
act(() => {
onChange(checked);
});
}}
>
<Checkbox data-testid="first-checkbox" value="sydney">
Sydney
</Checkbox>
<Checkbox data-testid="second-checkbox" value="buenos-aires">
Buenos Aires
</Checkbox>
</CheckboxGroup>,
);
const secondCheckbox = wrapper.getByTestId("second-checkbox");
await user.click(secondCheckbox);
expect(onChange).toHaveBeenCalledTimes(1);
expect(checked).toEqual(["sydney", "buenos-aires"]);
});
describe("validation", () => {
describe("validationBehavior=native", () => {
it("supports group level isRequired", async () => {
let {getAllByRole, getByRole, getByTestId} = render(
<form data-testid="form">
<CheckboxGroup isRequired label="Agree to the following" validationBehavior="native">
<Checkbox value="terms">Terms and conditions</Checkbox>
<Checkbox value="cookies">Cookies</Checkbox>
<Checkbox value="privacy">Privacy policy</Checkbox>
</CheckboxGroup>
</form>,
);
let group = getByRole("group");
expect(group).not.toHaveAttribute("aria-describedby");
let checkboxes = getAllByRole("checkbox") as HTMLInputElement[];
for (let input of checkboxes) {
expect(input).toHaveAttribute("required");
expect(input).not.toHaveAttribute("aria-required");
expect(input.validity.valid).toBe(false);
}
act(() => {
(getByTestId("form") as HTMLFormElement).checkValidity();
});
expect(group).toHaveAttribute("aria-describedby");
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent(
"Constraints not satisfied",
);
await user.click(checkboxes[0]);
for (let input of checkboxes) {
expect(input).not.toHaveAttribute("required");
expect(input).not.toHaveAttribute("aria-required");
expect(input.validity.valid).toBe(true);
}
expect(group).not.toHaveAttribute("aria-describedby");
});
it("supports checkbox level isRequired", async () => {
let {getAllByRole, getByRole, getByTestId} = render(
<form data-testid="form">
<CheckboxGroup label="Agree to the following" validationBehavior="native">
<Checkbox isRequired value="terms">
Terms and conditions
</Checkbox>
<Checkbox isRequired value="cookies">
Cookies
</Checkbox>
<Checkbox value="privacy">Privacy policy</Checkbox>
</CheckboxGroup>
</form>,
);
let group = getByRole("group");
expect(group).not.toHaveAttribute("aria-describedby");
let checkboxes = getAllByRole("checkbox") as HTMLInputElement[];
for (let input of checkboxes.slice(0, 2)) {
expect(input).toHaveAttribute("required");
expect(input).not.toHaveAttribute("aria-required");
expect(input.validity.valid).toBe(false);
}
expect(checkboxes[2]).not.toHaveAttribute("required");
expect(checkboxes[2]).not.toHaveAttribute("aria-required");
expect(checkboxes[2].validity.valid).toBe(true);
act(() => {
(getByTestId("form") as HTMLFormElement).checkValidity();
});
expect(group).toHaveAttribute("aria-describedby");
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent(
"Constraints not satisfied",
);
expect(document.activeElement).toBe(checkboxes[0]);
await user.click(checkboxes[0]);
await user.click(checkboxes[1]);
expect(checkboxes[0].validity.valid).toBe(true);
expect(checkboxes[1].validity.valid).toBe(true);
expect(group).not.toHaveAttribute("aria-describedby");
});
it("supports group level validate function", async () => {
let {getAllByRole, getByRole, getByTestId} = render(
<form data-testid="form">
<CheckboxGroup
label="Agree to the following"
validate={(v) => (v.length < 3 ? "You must accept all terms" : null)}
validationBehavior="native"
>
<Checkbox value="terms">Terms and conditions</Checkbox>
<Checkbox value="cookies">Cookies</Checkbox>
<Checkbox value="privacy">Privacy policy</Checkbox>
</CheckboxGroup>
</form>,
);
let group = getByRole("group");
expect(group).not.toHaveAttribute("aria-describedby");
let checkboxes = getAllByRole("checkbox") as HTMLInputElement[];
for (let input of checkboxes) {
expect(input).not.toHaveAttribute("required");
expect(input).not.toHaveAttribute("aria-required");
expect(input.validity.valid).toBe(false);
}
act(() => {
(getByTestId("form") as HTMLFormElement).checkValidity();
});
expect(group).toHaveAttribute("aria-describedby");
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent(
"You must accept all terms",
);
expect(document.activeElement).toBe(checkboxes[0]);
await user.click(checkboxes[0]);
expect(group).toHaveAttribute("aria-describedby");
for (let input of checkboxes) {
expect(input.validity.valid).toBe(false);
}
await user.click(checkboxes[1]);
expect(group).toHaveAttribute("aria-describedby");
for (let input of checkboxes) {
expect(input.validity.valid).toBe(false);
}
await user.click(checkboxes[2]);
expect(group).not.toHaveAttribute("aria-describedby");
for (let input of checkboxes) {
expect(input.validity.valid).toBe(true);
}
});
it("supports server validation", async () => {
function Test() {
const [serverErrors, setServerErrors] = React.useState({});
const onSubmit = (e) => {
e.preventDefault();
setServerErrors({
terms: "You must accept the terms.",
});
};
return (
<Form validationBehavior="native" validationErrors={serverErrors} onSubmit={onSubmit}>
<CheckboxGroup label="Agree to the following" name="terms">
<Checkbox value="terms">Terms and conditions</Checkbox>
<Checkbox value="cookies">Cookies</Checkbox>
<Checkbox value="privacy">Privacy policy</Checkbox>
</CheckboxGroup>
<button type="submit">Submit</button>
</Form>
);
}
const {getAllByRole, getByRole} = render(<Test />);
const group = getByRole("group");
expect(group).not.toHaveAttribute("aria-describedby");
const button = getByRole("button");
expect(button).toBeVisible();
await user.click(button);
expect(group).toHaveAttribute("aria-describedby");
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent(
"You must accept the terms.",
);
const checkboxes = getAllByRole("checkbox") as HTMLInputElement[];
for (let input of checkboxes) {
expect(input.validity.valid).toBe(false);
}
await user.click(checkboxes[0]);
expect(group).not.toHaveAttribute("aria-describedby");
for (let input of checkboxes) {
expect(input.validity.valid).toBe(true);
}
});
});
describe("validationBehavior=aria", () => {
it("supports group level validate function", async () => {
let {getAllByRole, getByRole} = render(
<CheckboxGroup
label="Agree to the following"
validate={(v) => (v.length < 3 ? "You must accept all terms" : null)}
validationBehavior="aria"
>
<Checkbox value="terms">Terms and conditions</Checkbox>
<Checkbox value="cookies">Cookies</Checkbox>
<Checkbox value="privacy">Privacy policy</Checkbox>
</CheckboxGroup>,
);
let group = getByRole("group");
expect(group).toHaveAttribute("aria-describedby");
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent(
"You must accept all terms",
);
let checkboxes = getAllByRole("checkbox") as HTMLInputElement[];
for (let input of checkboxes) {
expect(input).toHaveAttribute("aria-invalid", "true");
expect(input.validity.valid).toBe(true);
}
await user.click(checkboxes[0]);
expect(group).toHaveAttribute("aria-describedby");
await user.click(checkboxes[1]);
expect(group).toHaveAttribute("aria-describedby");
await user.click(checkboxes[2]);
expect(group).toHaveAttribute("aria-describedby");
});
it("supports server validation", async () => {
const {getAllByRole, getByRole} = render(
<Form validationBehavior="aria" validationErrors={{terms: "You must accept the terms"}}>
<CheckboxGroup label="Agree to the following" name="terms">
<Checkbox value="terms">Terms and conditions</Checkbox>
<Checkbox value="cookies">Cookies</Checkbox>
<Checkbox value="privacy">Privacy policy</Checkbox>
</CheckboxGroup>
</Form>,
);
const group = getByRole("group");
expect(group).toHaveAttribute("aria-describedby");
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent(
"You must accept the terms",
);
const checkboxes = getAllByRole("checkbox");
for (let input of checkboxes) {
expect(input).toHaveAttribute("aria-invalid", "true");
}
// TODO: Fix the following functions to work
// await user.click(checkboxes[0]);
// expect(group).not.toHaveAttribute("aria-describedby");
});
});
});
});