testing
Testing MUI components with React Testing Library — theme mocking, portal components, DataGrid, DatePicker, and accessibility testing
от TheLobbi★ 22 звезды на GitHub
Установить testing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Testing MUI Components
Comprehensive patterns for testing Material UI components with React Testing Library, covering theme integration, complex widgets, accessibility, and common pitfalls.
1. ThemeProvider Wrapper
MUI components rely on ThemeProvider for styling and behavior. Always wrap renders in your custom theme to get accurate test results.
renderWithTheme Utility
// test-utils.tsx
import { render, RenderOptions } from '@testing-library/react';
import { ThemeProvider, createTheme, Theme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { ReactElement } from 'react';
// Import your app's theme or create a default
const defaultTheme = createTheme({
palette: {
primary: { main: '#1976d2' },
secondary: { main: '#dc004e' },
},
typography: {
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
},
});
interface CustomRenderOptions extends Omit<RenderOptions, 'wrapper'> {
theme?: Theme;
}
export function renderWithTheme(
ui: ReactElement,
{ theme = defaultTheme, ...options }: CustomRenderOptions = {},
) {
function Wrapper({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
);
}
return render(ui, { wrapper: Wrapper, ...options });
}
// Re-export everything from RTL so tests import from one place
export * from '@testing-library/react';
export { renderWithTheme as render };
Usage
import { render, screen } from '../test-utils';
import { Button } from '@mui/material';
test('renders a primary button with theme colors', () => {
render(<Button variant="contained" color="primary">Save</Button>);
const button = screen.getByRole('button', { name: /save/i });
expect(button).toBeInTheDocument();
expect(button).toHaveClass('MuiButton-containedPrimary');
});
2. Portal Components
MUI Dialog, Menu, Popover, Snackbar, and Tooltip render into portals (appended to document.body). They are still found by RTL queries because RTL searches the entire document by default.
Testing Dialog
import { render, screen, waitFor } from '../test-utils';
import userEvent from '@testing-library/user-event';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
} from '@mui/material';
import { useState } from 'react';
function ConfirmDialog() {
const [open, setOpen] = useState(false);
const [confirmed, setConfirmed] = useState(false);
return (
<>
<Button onClick={() => setOpen(true)}>Delete</Button>
{confirmed && <span>Item deleted</span>}
<Dialog open={open} onClose={() => setOpen(false)}>
<DialogTitle>Confirm Delete</DialogTitle>
<DialogContent>Are you sure you want to delete this item?</DialogContent>
<DialogActions>
<Button onClick={() => setOpen(false)}>Cancel</Button>
<Button onClick={() => { setConfirmed(true); setOpen(false); }}>
Confirm
</Button>
</DialogActions>
</Dialog>
</>
);
}
test('opens dialog, confirms, and shows result', async () => {
const user = userEvent.setup();
render(<ConfirmDialog />);
// Dialog not visible yet
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
// Open the dialog
await user.click(screen.getByRole('button', { name: /delete/i }));
// Dialog is now visible (portal renders to body, but RTL finds it)
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByText(/are you sure/i)).toBeInTheDocument();
// Confirm
await user.click(screen.getByRole('button', { name: /confirm/i }));
// Dialog closed, result shown
await waitFor(() => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
expect(screen.getByText(/item deleted/i)).toBeInTheDocument();
});
Testing Menu
test('opens menu and selects an option', async () => {
const user = userEvent.setup();
const onSelect = vi.fn();
render(
<MenuExample onSelect={onSelect} />
);
// Open menu
await user.click(screen.getByRole('button', { name: /options/i }));
// Menu items are in a portal but queryable
const menuItems = screen.getAllByRole('menuitem');
expect(menuItems).toHaveLength(3);
// Select an item
await user.click(screen.getByRole('menuitem', { name: /edit/i }));
expect(onSelect).toHaveBeenCalledWith('edit');
// Menu closes after selection
await waitFor(() => {
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
});
});
Testing Snackbar
test('shows snackbar on action and auto-hides', async () => {
const user = userEvent.setup();
// Use fake timers for autoHideDuration
vi.useFakeTimers({ shouldAdvanceTime: true });
render(<SnackbarExample />);
await user.click(screen.getByRole('button', { name: /save/i }));
expect(screen.getByRole('alert')).toHaveTextContent(/saved successfully/i);
// A
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
- 01
Read - 02
Glob - 03
Grep - 04
Bash - 05
Write - 06
Edit
FAQ
Что делает скилл testing?
Testing MUI components with React Testing Library — theme mocking, portal components, DataGrid, DatePicker, and accessibility testing
Как установить скилл testing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл testing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
AnthropicToolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
access
AnthropicManage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
configure
AnthropicSet up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
access
AnthropicManage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…