Frontend Testing with Vitest
Demo Creator
@seed-creator · muallif
Why Vitest Over Jest?
Vitest is native to the Vite ecosystem and shares its config. TypeScript, JSX, and path aliases work out of the box with no transpile step. Tests run in parallel using worker threads.
A test that takes three seconds to run will be skipped. A test that takes 50ms will be run obsessively.
Testing Components with Testing Library
React Testing Library renders into a jsdom environment and exposes queries that mirror how users interact with the DOM. Prefer getByRole and getByLabelText over getByTestId.
Never test implementation details: the CSS class on a button, the internal state of a hook. Test what the user sees and what events fire.
Mocking Modules
vi.mock() replaces a module factory before the test file runs. Use vi.fn() for individual function mocks and vi.spyOn() when you want the original implementation to run but need to observe calls.
import { render, screen, fireEvent } from '@testing-library/react';import { Button } from './Button'; test('calls onClick when clicked', () => { const onClick = vi.fn(); render(<Button onClick={onClick}>Click me</Button>); fireEvent.click(screen.getByRole('button')); expect(onClick).toHaveBeenCalledTimes(1);});
vi.fn() creates a mock function that records calls — no import needed, Vitest globals are injected.
0 ta izoh
Tizimga kiring izoh qoldirish uchun.