|
1 | | -import { describe, expect, test, beforeEach } from "vitest"; |
| 1 | +import { describe, expect, test, beforeEach, vi } from "vitest"; |
2 | 2 | import { render, screen, cleanup } from "@testing-library/react"; |
3 | 3 | import { cva, VariantProps } from "class-variance-authority"; |
4 | 4 | import { twc, createTwc, TwcComponentProps } from "./index"; |
|
9 | 9 | ButtonProps as AriaButtonProps, |
10 | 10 | } from "react-aria-components"; |
11 | 11 | import * as AccordionPrimitive from "@radix-ui/react-accordion"; |
| 12 | +import { Slot } from "@radix-ui/react-slot"; |
12 | 13 |
|
13 | 14 | describe("twc", () => { |
14 | 15 | beforeEach(cleanup); |
@@ -228,6 +229,38 @@ describe("twc", () => { |
228 | 229 | expect(title.classList.contains("text-xl")).toBe(true); |
229 | 230 | }); |
230 | 231 |
|
| 232 | + test('forwards "asChild" property to custom component when "shouldForwardAsChild" is true', () => { |
| 233 | + const twx = createTwc({ |
| 234 | + shouldForwardAsChild: true, |
| 235 | + }); |
| 236 | + |
| 237 | + type PrimitiveProps = React.ButtonHTMLAttributes<HTMLButtonElement> & { |
| 238 | + asChild?: boolean; |
| 239 | + }; |
| 240 | + |
| 241 | + const handleClick = vi.fn<[React.MouseEvent<HTMLButtonElement>], void>() |
| 242 | + const Primitive = ({ asChild, ...props }: PrimitiveProps) => { |
| 243 | + const Comp = asChild ? Slot : 'button' |
| 244 | + return <Comp onClick={handleClick} {...props}/>; |
| 245 | + }; |
| 246 | + |
| 247 | + const StyledPrimitive = twx(Primitive)`text-xl` |
| 248 | + |
| 249 | + render( |
| 250 | + <StyledPrimitive asChild> |
| 251 | + <a>Click me!</a> |
| 252 | + </StyledPrimitive> |
| 253 | + ) |
| 254 | + |
| 255 | + const element = screen.getByText('Click me!') |
| 256 | + element.click() |
| 257 | + |
| 258 | + expect(element.tagName).toBeDefined() |
| 259 | + expect(element.tagName).toBe('A') |
| 260 | + expect(element.classList.contains('text-xl')).toBe(true) |
| 261 | + expect(handleClick).toBeCalled() |
| 262 | + }); |
| 263 | + |
231 | 264 | test("works with tailwind-merge", () => { |
232 | 265 | const twx = createTwc({ |
233 | 266 | compose: twMerge, |
|
0 commit comments