import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
} from './dropdown-menu';
import React from 'react';
// Mocking Portal
vi.mock('@radix-ui/react-dropdown-menu', async () => {
const actual = await vi.importActual('@radix-ui/react-dropdown-menu');
return {
...actual,
Portal: ({ children }: { children: React.ReactNode }) => (
{children}
),
};
});
describe('DropdownMenu', () => {
it('renders correctly', () => {
render(
Open
My Account
Profile
Settings
);
expect(screen.getByText('Open')).toBeInTheDocument();
});
it('shows content when open is true', () => {
render(
Open
Option 1
);
expect(screen.getByText('Option 1')).toBeInTheDocument();
});
it('has correct data-slot attributes', () => {
const { container } = render(
Open
);
expect(container.querySelector('[data-slot="dropdown-menu-trigger"]')).toBeInTheDocument();
});
it('opens content when the trigger is clicked', async () => {
const user = userEvent.setup();
render(
Open
Profile
);
expect(screen.queryByText('Profile')).not.toBeInTheDocument();
await user.click(screen.getByText('Open'));
await waitFor(() => {
expect(screen.getByText('Profile')).toBeInTheDocument();
});
});
it('closes when Escape is pressed', async () => {
const user = userEvent.setup();
render(
Open
Profile
);
await user.click(screen.getByText('Open'));
await waitFor(() => {
expect(screen.getByText('Profile')).toBeInTheDocument();
});
await user.keyboard('{Escape}');
await waitFor(() => {
expect(screen.queryByText('Profile')).not.toBeInTheDocument();
});
});
it('closes when an item is selected', async () => {
const user = userEvent.setup();
const onSelect = vi.fn();
render(
Open
Profile
);
await user.click(screen.getByText('Open'));
await waitFor(() => {
expect(screen.getByText('Profile')).toBeInTheDocument();
});
await user.click(screen.getByText('Profile'));
await waitFor(() => {
expect(onSelect).toHaveBeenCalled();
});
await waitFor(() => {
expect(screen.queryByText('Profile')).not.toBeInTheDocument();
});
});
});