How to Write Unit and Integration Tests for Ant Design Components with Jest
Ant Design provides a standardized testing framework using Jest and @testing-library/react, offering shared helpers like mountTest, rtlTest, and a custom render utility in tests/utils.tsx to ensure consistent unit and integration coverage.
Writing comprehensive tests for Ant Design (antd) components requires following the library's established patterns to ensure compatibility with React StrictMode, theme configurations, and accessibility standards. This guide demonstrates how to write unit and integration tests for Ant Design components with Jest, leveraging the shared testing infrastructure found in the ant-design/ant-design repository.
Shared Testing Helpers
Ant Design ships with three reusable testing utilities that enforce baseline behavior across all components. These helpers are located in the tests/shared/ directory and should be imported into every component test suite.
mountTest
The mountTest helper verifies that a component can mount and unmount without throwing errors. This catches common lifecycle issues and memory leaks.
import mountTest from '../../../tests/shared/mountTest';
import Button from '..';
describe('Button', () => {
mountTest(Button);
});
Source: tests/shared/mountTest.tsx
rtlTest
The rtlTest helper checks that components render correctly in right-to-left (RTL) direction by wrapping the component in a ConfigProvider with direction="rtl" and comparing against a snapshot.
import rtlTest from '../../../tests/shared/rtlTest';
describe('Button', () => {
rtlTest(Button);
});
Source: tests/shared/rtlTest.tsx
Custom render Utility
The render function exported from tests/utils.tsx wraps @testing-library/react's render with React StrictMode enabled. It also provides mock date helpers, resize triggers, and fake timer utilities essential for testing Ant Design's date pickers and responsive components.
import { render, fireEvent } from '../../../tests/utils';
it('handles click events', () => {
const handleClick = jest.fn();
const { getByRole } = render(<Button onClick={handleClick}>Click</Button>);
fireEvent.click(getByRole('button'));
expect(handleClick).toHaveBeenCalled();
});
Source: tests/utils.tsx
Test File Layout
Component tests are organized within __tests__ directories following a consistent structure. For example, the Button component uses this layout:
components/
button/
__tests__/
index.test.tsx ← Main unit tests
semantic.test.tsx ← Semantic HTML checks
demo.test.tsx ← Demo snippet rendering
a11y.test.tsx ← Accessibility assertions
The index.test.tsx file serves as the primary entry point for unit tests, importing the component, shared helpers, and rendering utilities.
Writing Unit Tests for Ant Design Components
Unit tests focus on individual component behavior: props, state management, event handling, and DOM output.
Testing Props and Variants
Test each public prop in isolation to ensure correct CSS class application and behavior. The Button component tests in components/button/__tests__/index.test.tsx demonstrate patterns for testing loading, disabled, type, danger, and ghost props.
it('applies loading class and ignores clicks when loading', () => {
const onClick = jest.fn();
const { container, getByRole } = render(
<Button loading onClick={onClick}>Loading</Button>
);
expect(container.querySelector('.ant-btn-loading')).toBeTruthy();
fireEvent.click(getByRole('button'));
expect(onClick).not.toHaveBeenCalled();
});
Event Handling Patterns
Use fireEvent from the custom utils to simulate user interactions. Verify that callbacks fire with correct arguments and that disabled states prevent unwanted actions.
it('calls onClick with event when clicked', () => {
const handleClick = jest.fn();
const { getByRole } = render(<Button onClick={handleClick}>Click Me</Button>);
fireEvent.click(getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
Snapshot Testing
Capture component markup to detect unintended changes. The custom render returns a container object suitable for snapshotting.
it('matches snapshot with icon', () => {
const { container } = render(
<Button icon={<SearchOutlined />}>Search</Button>
);
expect(container.firstChild).toMatchSnapshot();
});
Snapshots are stored in __snapshots__/ alongside the test file and update via npm run test:update.
Writing Integration Tests for Ant Design Components
Integration tests verify component behavior within React context, including theme providers, directionality, and global configuration.
Testing with ConfigProvider and Theme
Wrap components in ConfigProvider to test theme algorithms, custom tokens, and RTL direction. The Button integration tests in components/button/__tests__/index.test.tsx demonstrate validating dark mode token overrides.
import ConfigProvider from '../../config-provider';
import theme from '../../theme';
it('applies dark token overrides', () => {
const { container } = render(
<ConfigProvider theme={{ algorithm: [theme.darkAlgorithm] }}>
<Button color="default" variant="solid">Dark</Button>
</ConfigProvider>
);
expect(container.firstChild).toHaveStyle({
'--ant-button-solid-text-color': '#000'
});
});
RTL Integration Testing
While rtlTest provides baseline coverage, custom integration tests may need to verify specific RTL behavior. Use ConfigProvider with direction="rtl" and query for direction-specific attributes.
it('renders with RTL direction', () => {
const { container } = render(
<ConfigProvider direction="rtl">
<Button>RTL Button</Button>
</ConfigProvider>
);
expect(container.querySelector('.ant-btn')).toHaveAttribute('dir', 'rtl');
});
Accessibility Integration
Dedicated accessibility tests use jest-axe to validate WCAG compliance. Create a11y.test.tsx files for interactive components.
import { render } from '../../../tests/utils';
import { axe } from 'jest-axe';
import Button from '..';
it('has no axe violations', async () => {
const { container } = render(<Button>Accessible</Button>);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
Source: components/button/__tests__/a11y.test.tsx
Essential Testing Utilities
Ant Design's test suite provides specialized utilities in tests/utils.tsx for handling complex component behaviors.
Fake Timers and Async Operations
Components like DatePicker or Tooltip rely on timers. Use waitFakeTimer to advance Jest timers and flush promises.
import { render, waitFakeTimer } from '../../../tests/utils';
it('shows tooltip after delay', async () => {
const { container } = render(<Tooltip title="Help" mouseEnterDelay={1000}><Button>Hover</Button></Tooltip>);
fireEvent.mouseEnter(container.firstChild!);
await waitFakeTimer();
expect(document.querySelector('.ant-tooltip')).toBeTruthy();
});
Resize Simulation
Test responsive behavior using triggerResize, which fires synthetic resize events on DOM elements.
import { render, triggerResize } from '../../../tests/utils';
it('adjusts layout on resize', () => {
const { container } = render(<ResponsiveComponent />);
triggerResize(container.firstChild!);
// Assert layout changes
});
Running Tests in the Ant Design Repository
The repository configures Jest through jest.config.js and setup files located in tests/setup.ts and tests/setupAfterEnv.ts. Execute tests using npm scripts:
# Run all tests
npm test
# Run tests for a specific component
npm test -- components/button
# Update snapshots after intentional UI changes
npm run test:update
# Run visual regression tests (separate script)
npm run test:image
Summary
- Reuse shared helpers (
mountTest,rtlTest) fromtests/shared/to enforce baseline mount and RTL behavior across all components. - Import
renderfromtests/utils.tsxto ensure React StrictMode consistency and access to fake timers and resize utilities. - Structure tests in
__tests__/index.test.tsxfor unit tests,a11y.test.tsxfor accessibility, anddemo.test.tsxfor demo validation. - Test props individually using
fireEventfor interactions and snapshotting for markup stability. - Validate integration by wrapping components in
ConfigProviderwith theme algorithms and RTL direction. - Execute with
npm testand update snapshots vianpm run test:updatewhen making intentional changes.
Frequently Asked Questions
What testing libraries does Ant Design use for component testing?
Ant Design uses Jest as the test runner combined with @testing-library/react for DOM testing utilities. The repository provides a custom render wrapper in tests/utils.tsx that enforces React StrictMode and includes additional helpers for fake timers and resize events.
How do I test Ant Design components with different themes or RTL layouts?
Wrap your component in ConfigProvider and specify the theme algorithm or direction prop. For baseline coverage, import rtlTest from tests/shared/rtlTest.tsx, which automatically renders your component in RTL mode and validates the output against a snapshot.
What is the purpose of the mountTest and rtlTest helpers?
mountTest verifies that a component can mount and unmount without throwing errors, catching lifecycle issues and memory leaks. rtlTest ensures components render correctly in right-to-left contexts, which is critical for internationalization support in Ant Design's global user base.
How do I handle asynchronous operations like timers in Ant Design tests?
Import waitFakeTimer from tests/utils.tsx to advance Jest's fake timers and flush pending promises. This utility is essential for testing components with delayed interactions, such as tooltips, dropdowns, or date pickers that rely on timeout-based visibility changes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →