shadcnui

How do I get a Shadcn button's variant for testing?


For testing purposes, I want to check if my <Button /> component is of the "disabled" variant, however I'm not sure how to check for that.

it('renders disabled button', () => {
  render(<Button variant="disabled" />);

  const button = screen.getByRole("button");
  
  // How would I get the variant of button?
})

In general, how can I get the variant of a Shadcn Button component for my tests?


Solution

  • You can use the toHaveClass() method and grab the associated classes from the buttonVariants variable exported by the Button component.

    In your code you can do:

    import { Button, buttonVariants } from "@/components/ui/button";
    
    it('renders disabled button', () => {
      render(<Button variant="disabled" />);
    
      const button = screen.getByRole("button");
    
      const expectedClass = buttonVariants({ variant: "disabled" })
      expect(button).toHaveClass(expectedClass)
    })