Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Next.js and Tooling

Tooling: TypeScript, Testing, Migration

Set up Material UI with Vite and TypeScript, type sx and wrappers, test components with Testing Library, lint imports and upgrade between major versions.

A component library only pays off if the surrounding tools fit: a fast dev server, types that catch mistakes, tests that survive redesigns and a safe route through major upgrades. This lesson covers the practical tooling around Material UI: a Vite setup, TypeScript patterns for sx and wrappers, testing with React Testing Library, lint rules, and the migration steps between versions.

MUI, Vite and the testing tools are not available in the live editors on this site. The real commands and code are read-only. The runnable examples are stand-ins: a tiny accessibility-based query helper that works like Testing Library, and a migration helper that rewrites deprecated props.

A Vite project

Vite is a popular choice for single-page apps:

Terminal
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install @mui/material @emotion/react @emotion/styled @fontsource/roboto @mui/icons-material

Then load the font once and wrap the app:

TSX
// Real Material UI + Vite, read-only: src/main.tsx
import '@fontsource/roboto/300.css';
import '@fontsource/roboto/400.css';
import '@fontsource/roboto/500.css';
import '@fontsource/roboto/700.css';

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import theme from './theme';
import App from './App';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <App />
    </ThemeProvider>
  </StrictMode>,
);

Useful extras in vite.config.ts: path aliases (@/ui), a manualChunks rule that puts @mui in its own long-cacheable chunk, and the bundle visualizer plugin (see Bundle Size and Imports). Vite does not need SSR setup unless you add it yourself.

TypeScript patterns

MUI is written in TypeScript, so the types are accurate and rich. A few patterns come up constantly.

Typing sx

TSX
// Real Material UI + TypeScript, read-only
import type { SxProps, Theme } from '@mui/material/styles';

const cardSx: SxProps<Theme> = {
  p: 2,
  bgcolor: 'background.paper',
};

type Props = { sx?: SxProps<Theme> };

function Panel({ sx }: Props) {
  return <Box sx={[cardSx, ...(Array.isArray(sx) ? sx : [sx])]} />;
}

Define sx objects outside the component with SxProps<Theme> so they are stable and type-checked. When you declare them as a plain object literal with as const, some properties (like position: 'absolute') widen to string and fail; the SxProps<Theme> annotation avoids this.

Extending component props

TSX
// Real Material UI + TypeScript, read-only
import Button, { type ButtonProps } from '@mui/material/Button';

type SaveButtonProps = Omit<ButtonProps, 'type' | 'children'> & {
  saving?: boolean;
};

export function SaveButton({ saving = false, disabled, ...props }: SaveButtonProps) {
  return (
    <Button type="submit" variant="contained" disabled={disabled || saving} {...props}>
      {saving ? 'Saving...' : 'Save'}
    </Button>
  );
}

The component prop and generics

A component with component={Link} gets the link's props typed too. In wrappers, the helper type is OverridableComponent or you can type the wrapper with ButtonProps<'a'> / ButtonProps<typeof RouterLink>. If TypeScript becomes slow or errors get long, simplify: pass href or to to a dedicated component (LinkButton) with narrow props.

Theme augmentation

Custom palette colors, variants and breakpoints need module augmentation. Put it in a theme.d.ts that your tsconfig includes. See Component Overrides and Variants.

Strictness

Turn on strict and noUncheckedIndexedAccess in tsconfig.json; MUI's event types (SelectChangeEvent, React.ChangeEvent<HTMLInputElement>) work best with them. Select's onChange receives SelectChangeEvent<string>, not a normal change event: its value is event.target.value.

Testing with Testing Library

Test components the way a user finds them: by role, label and visible text, not by class names (MUI class names are generated and can change). The standard stack is Vitest or Jest, React Testing Library and user-event.

TSX
// Real Vitest + Testing Library + Material UI, read-only
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider } from '@mui/material/styles';
import theme from './theme';
import { SaveButton } from './SaveButton';

function renderWithTheme(ui: React.ReactElement) {
  return render(<ThemeProvider theme={theme}>{ui}</ThemeProvider>);
}

test('submits when clicked', async () => {
  const onClick = vi.fn();
  renderWithTheme(<SaveButton onClick={onClick} />);

  await userEvent.click(screen.getByRole('button', { name: /save/i }));

  expect(onClick).toHaveBeenCalledTimes(1);
});

test('shows a busy label and is disabled while saving', () => {
  renderWithTheme(<SaveButton saving />);
  expect(screen.getByRole('button', { name: /saving/i })).toBeDisabled();
});

Tips for MUI specifically:

  • Menus, dialogs and selects render in portals (outside your container). screen queries the whole document, so use screen, not the object returned by render.
  • A MUI Select is not a native <select>; open it with userEvent.click(screen.getByRole('combobox', { name: /status/i })), then pick screen.getByRole('option', { name: 'Paid' }).
  • TextField labels are wired to inputs, so getByLabelText('Email') works. If it does not, the id is probably missing.
  • Transitions delay removal. Use await waitForElementToBeRemoved(...) or findBy* queries for things that animate in or out; or set transitionDuration={0} through the theme in tests.
  • Do not assert on class names or inline styles; assert on roles, states (aria-expanded, aria-selected, disabled) and text.

Try it: queries by role and name

Testing Library finds elements by their accessible role and name. This stand-in implements a simplified getByRole and runs a few "tests" against a rendered form. Change the form (for example remove an aria-label) and watch a test fail, which is exactly how these tests find accessibility problems.

A tiny getByRole and test runner

Notice that the failing test is a real accessibility bug: a screen reader user also could not find that button. Role-based tests double as accessibility checks. Add jest-axe or vitest-axe for automated axe rules on rendered output.

Linting and formatting

  • ESLint with eslint-plugin-react-hooks and eslint-plugin-jsx-a11y; both catch common mistakes in MUI code.
  • A no-restricted-imports rule that blocks deep imports (@mui/*/*/*) and, if you chose path imports, barrel imports.
  • Prettier for formatting; no special config for MUI.
  • tsc --noEmit in CI, so type errors fail the build.

Upgrading MUI

MUI follows semantic versioning with a published migration guide for each major version. A safe routine:

  1. Read the migration guide for the target version before you touch the code.
  2. Upgrade all @mui/* packages together (and @emotion/* if the guide requires it), so there is one version of each.
  3. Run the official codemods: npx @mui/codemod@latest <codemod-name> <path>. They rewrite renamed props, imports and components for you.
  4. Run type checks and tests; fix remaining errors file by file.
  5. Check the app visually, especially spacing, typography and dark mode, since defaults sometimes change.
  6. Remove the deprecated APIs gradually: deprecated props still work for a while and log warnings.

Examples of changes across recent versions (check the exact guide for yours): Grid v2 became the main Grid with a size prop, TextField and other inputs moved from InputProps-style props to slotProps, components/componentsProps became slots/slotProps, and extendTheme was folded into createTheme with cssVariables.

Try it: rewriting a deprecated prop

Codemods work on the syntax tree, but the idea is simple to see with a text rewrite. This stand-in converts the old InputProps / inputProps style into slotProps for a TextField. It is a toy (the real codemod parses code), but it shows what the migration changes.

From InputProps to slotProps

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why prefer getByRole and getByLabelText over class-name selectors in MUI tests?

    Tests tied to roles, labels and text survive redesigns and fail when something becomes inaccessible.
  2. 2. A MUI Menu is open and you cannot find its items with the object returned by render(). Why?

    Menus, dialogs and popovers mount in document.body. screen queries the entire document.
  3. 3. What is the safest way to upgrade MUI to a new major version?

    A planned upgrade uses the guide and codemods, with one consistent version of each package.
  4. 4. How do you type a reusable sx variable?

    SxProps<Theme> gives accurate checking and avoids widening of literal values such as position.

Summary

  • A Vite + TypeScript template plus the font, ThemeProvider and CssBaseline is a complete starting point.
  • Type sx with SxProps<Theme>, extend ButtonProps and friends in wrappers, and augment the theme in a .d.ts.
  • Test by role, label and text with Testing Library and screen (portals); await transitions.
  • Lint imports and accessibility; run tsc in CI.
  • Upgrade with the migration guide, matching package versions and the official codemods.

Next: Project: Admin Dashboard