@ehsaneha/react-slot
Version:
A React <Slot> component that merges props and forwards refs to a single child element, similar to Radix UI’s Slot.
45 lines (44 loc) • 2.25 kB
JavaScript
import React, { createRef } from "react";
import { render, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom";
import Slot from "./index";
describe("<Slot />", () => {
test("renders child element correctly", () => {
const { getByText } = render(React.createElement(Slot, { className: "test-class" },
React.createElement("button", null, "Click me")));
const button = getByText("Click me");
expect(button).toBeInTheDocument();
expect(button).toHaveClass("test-class");
});
test("merges className and style props", () => {
const { getByText } = render(React.createElement(Slot, { className: "slot-class", style: { color: "red" } },
React.createElement("button", { className: "child-class", style: { backgroundColor: "blue" } }, "Button")));
const button = getByText("Button");
expect(button).toHaveClass("slot-class");
expect(button).toHaveClass("child-class");
expect(button).toHaveStyle("color: rgb(255, 0, 0)");
expect(button).toHaveStyle("background-color: rgb(0, 0, 255)");
});
test("merges onClick handlers and calls both", () => {
const slotClick = jest.fn();
const childClick = jest.fn();
const { getByText } = render(React.createElement(Slot, { onClick: slotClick },
React.createElement("button", { onClick: childClick }, "Click me")));
const button = getByText("Click me");
fireEvent.click(button);
expect(slotClick).toHaveBeenCalledTimes(1);
expect(childClick).toHaveBeenCalledTimes(1);
});
test("forwards ref to child element", () => {
var _a;
const ref = createRef();
render(React.createElement(Slot, { ref: ref },
React.createElement("button", null, "Button")));
expect(ref.current).toBeInstanceOf(HTMLButtonElement);
expect((_a = ref.current) === null || _a === void 0 ? void 0 : _a.textContent).toBe("Button");
});
test("handles invalid child gracefully", () => {
const { container } = render(React.createElement(Slot, null, null));
expect(container.firstChild).toBeNull();
});
});