Guide
The State of JavaScript Testing in 2026



Choose JavaScript testing tools for your app. Compare Vitest and Jest for unit tests, Testing Library for React components, and Playwright for browser tests.
Contents
Contents
TL;DR
Start with Vitest for unit tests in a Vite project, Testing Library for React component interactions, and Playwright Test for cross-browser E2E. Keep Jest where the existing suite depends on its transforms or tooling. Keep Cypress if component testing and the interactive runner already fit your workflow.
Key Takeaways
- Vitest can reuse your Vite configuration for tests.
- Jest remains a practical choice for suites with custom transforms, reporters, or environment setup.
- Playwright runs browser projects across Chromium, Firefox, and WebKit.
- Testing Library helps you test what users can find and interact with in the DOM.
- Cypress combines browser E2E with a dedicated component testing workflow.
The Test Stack in 2026
Unit/Integration Tests: Vitest + Testing Library (React/Vue/Svelte)
E2E Tests: Playwright
Component Testing: Vitest + Testing Library OR Playwright component tests
Visual Testing: Playwright screenshots + Percy/Chromatic
API Testing: Vitest (unit) OR Playwright (integration)
Vitest (Unit Testing)
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'happy-dom',
globals: true, // No need to import describe/it/expect
setupFiles: ['./src/test/setup.ts'],
coverage: {
provider: 'v8', // Native V8 coverage (fast)
reporter: ['text', 'html', 'lcov'],
exclude: ['**/*.d.ts', '**/index.ts', '**/*.config.*'],
},
},
});
// Example: Testing a utility function
// src/lib/health-score.test.ts
import { describe, it, expect } from 'vitest';
import { calculateHealthScore } from './health-score';
describe('calculateHealthScore', () => {
it('returns 100 for a perfect package', () => {
const score = calculateHealthScore({
weeksSinceLastRelease: 2,
openIssues: 5,
hasTests: true,
hasTypeScript: true,
downloadTrend: 'up',
});
expect(score).toBe(100);
});
it('penalizes packages not updated in 2 years', () => {
const score = calculateHealthScore({
weeksSinceLastRelease: 104, // 2 years
openIssues: 50,
hasTests: false,
hasTypeScript: false,
downloadTrend: 'down',
});
expect(score).toBeLessThan(30);
});
it.each([
[4, 90], // 4 weeks → 90%
[26, 70], // 26 weeks → 70%
[52, 50], // 52 weeks → 50%
])('weeksSinceLastRelease=%i gives score near %i', (weeks, expectedMin) => {
const score = calculateHealthScore({ weeksSinceLastRelease: weeks });
expect(score).toBeGreaterThanOrEqual(expectedMin - 10);
});
});
// Vitest — mocking (vi = jest equivalent)
import { vi, describe, it, expect, beforeEach } from 'vitest';
import { fetchPackageData } from './npm-api';
import { getPackageHealth } from './health';
vi.mock('./npm-api'); // Auto-mock the module
describe('getPackageHealth', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('fetches data and computes health', async () => {
vi.mocked(fetchPackageData).mockResolvedValue({
name: 'example-kit',
weeklyDownloads: 120,
lastPublish: new Date('2026-03-01'),
});
const health = await getPackageHealth('example-kit');
expect(fetchPackageData).toHaveBeenCalledWith('example-kit');
expect(health.score).toBeGreaterThan(80);
expect(health.name).toBe('example-kit');
});
});
Vitest is a natural fit for projects that already use Vite. When the test runner uses the same aliases and transforms as the app, imports resolve the same way in both places.
Inspect your Jest transforms before switching. A project that transpiles ESM to CommonJS in tests can behave differently from the application build. Check ESM-only dependencies, aliases, and the purpose of each transformIgnorePatterns exception. Jest also has an experimental ESM mode.
Vitest supports ESM and TypeScript through Vite. Start with the app's Vite configuration, add a test section, and check any test-only environment and setup files. Run your separate TypeScript check so it still covers the test files.
Port a representative suite first. Keep the familiar describe, it, and expect calls, then translate jest.mock and jest.fn to their vi counterparts. Verify module mocks, fake timers, and setup-file behavior before moving the rest of the suite.
Testing Library (React Component Tests)
// Testing Library — test user behavior, not implementation
// src/components/PackageCard.test.tsx
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { PackageCard } from './PackageCard';
describe('PackageCard', () => {
const mockPackage = {
name: 'zustand',
description: 'Simple state management',
weeklyDownloads: 4_000_000,
healthScore: 92,
};
it('renders package name and health score', () => {
render(<PackageCard pkg={mockPackage} />);
expect(screen.getByRole('heading', { name: 'zustand' })).toBeInTheDocument();
expect(screen.getByText('92/100')).toBeInTheDocument();
});
it('calls onSelect when clicked', async () => {
const user = userEvent.setup();
const onSelect = vi.fn();
render(<PackageCard pkg={mockPackage} onSelect={onSelect} />);
await user.click(screen.getByRole('button', { name: /compare/i }));
expect(onSelect).toHaveBeenCalledWith('zustand');
});
it('shows loading state while fetching details', async () => {
render(<PackageCard pkg={mockPackage} loadDetails />);
expect(screen.getByRole('progressbar')).toBeInTheDocument();
await waitFor(() => {
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
});
});
});
// Testing Library query priority (2026 best practices)
// ✅ Best: accessible queries (test what users see)
screen.getByRole('button', { name: 'Submit' })
screen.getByLabelText('Email address')
screen.getByPlaceholderText('Search packages')
// ✅ Good: text content
screen.getByText('Download trends')
screen.getByTitle('Health score')
// ⚠️ Acceptable when needed
screen.getByTestId('package-grid')
// ❌ Avoid: implementation details
screen.getByClassName('btn-primary')
document.querySelector('.card')
Testing Library's "don't test implementation details" philosophy has proven durable in a way that its alternatives haven't. Earlier React testing approaches tested internal component state, prop drilling, and DOM structure — tests that broke on every refactor. Testing Library's accessible queries (getByRole, getByLabelText) test what a screen reader and real user would interact with. These tests survive internal component refactors, state management library changes, and CSS restructuring as long as the user-visible behavior remains the same.
The practical benefit is lower maintenance overhead on tests over time. A test that uses screen.getByRole('button', { name: 'Submit' }) continues working when you rename an internal CSS class, move the button to a different component, or switch from useState to Zustand. A test that uses document.querySelector('.btn-primary') breaks on any of these changes. Teams that adopted Testing Library early report that their 2021 test files still pass in 2026 with minimal modification — the behavioral approach ages better than the structural approach.
The one limitation worth understanding: Testing Library tests don't test CSS or visual layout. If your "Submit" button is positioned off-screen by a CSS bug, getByRole('button', { name: 'Submit' }) will still find it and clicking it will still work — because Testing Library fires JavaScript events, not real browser clicks. For layout and visual testing, you need Playwright's pixel comparison (screenshots plus Chromatic or Percy) or explicit tests of CSS property values. This isn't a failure of Testing Library's philosophy; it's a scope boundary. Use Testing Library for behavioral testing, Playwright screenshots for visual testing.
Playwright (E2E Testing)
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true, // Run tests in parallel
forbidOnly: !!process.env.CI, // Fail if test.only left in code
retries: process.env.CI ? 2 : 0,
reporter: [['html'], ['github']],
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry', // Record trace on failure
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'mobile', use: { ...devices['iPhone 14'] } },
],
webServer: {
command: 'npm run dev', // Start app before tests
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
});
// e2e/package-search.spec.ts
import { test, expect, Page } from '@playwright/test';
test.describe('Package Search', () => {
test('searches for a package and shows comparison', async ({ page }) => {
await page.goto('/');
// Fill search — Playwright auto-waits for element to be visible
await page.getByPlaceholder('Search npm packages...').fill('react');
await page.keyboard.press('Enter');
// Assert results
await expect(page.getByRole('heading', { name: 'react' })).toBeVisible();
await expect(page.getByText(/weekly downloads/i)).toBeVisible();
});
test('compares two packages', async ({ page }) => {
await page.goto('/compare/react-vs-vue');
await expect(page.getByRole('heading', { name: /react vs vue/i })).toBeVisible();
// Check health scores visible
const scores = page.getByTestId('health-score');
await expect(scores).toHaveCount(2);
});
test('mobile navigation works', async ({ page }) => {
// Test at mobile viewport
await page.setViewportSize({ width: 375, height: 812 });
await page.goto('/');
await page.getByRole('button', { name: 'Menu' }).click();
await expect(page.getByRole('navigation')).toBeVisible();
});
});
// Playwright — Page Object Model (for larger test suites)
class SearchPage {
constructor(private page: Page) {}
async search(query: string) {
await this.page.getByPlaceholder('Search npm packages...').fill(query);
await this.page.keyboard.press('Enter');
await this.page.waitForURL(/\?q=/);
}
async getFirstResult() {
return this.page.getByTestId('package-result').first();
}
}
test('search returns results', async ({ page }) => {
const searchPage = new SearchPage(page);
await page.goto('/');
await searchPage.search('zustand');
const first = await searchPage.getFirstResult();
await expect(first).toBeVisible();
});
Playwright Test supports projects for Chromium, Firefox, and WebKit. Use browser projects to run the same critical flow across engines, then use locators and retrying assertions to wait for the state the user should see.
Both tools can retry assertions. In Playwright, a locator action waits for the checks that apply to that action, and expect(locator).toBeVisible() retries until the target is visible or the assertion times out. In Cypress, an aliased intercept lets you wait for a specific request when that request is part of the flow.
Add a WebKit project if Safari users matter to your application, and retain real Safari checks for behavior that depends on the shipping browser or device. Cypress supports Chrome-family browsers and Firefox, with experimental WebKit support.
The programming model difference matters less than teams expect before switching. Cypress's Chaining API (cy.get().click().should()) is syntactically elegant; Playwright's async/await pattern (await page.click(); await expect(locator).toBeVisible()) feels more like standard JavaScript. Both work; Playwright's model integrates more naturally with TypeScript's type inference for complex test interactions.
Jest vs Vitest: Why the Switch
| Factor | Jest | Vitest |
|---|---|---|
| ESM | Experimental mode, with ESM-compatible transforms if used | Runs through Vite's module tooling |
| TypeScript | Can use a transformer such as Babel or ts-jest | Uses Vite's TypeScript transform |
| Watch mode | Available in Jest | Available in Vitest |
| Test configuration | Jest config and any custom transformers | App Vite config or a separate Vitest config |
| Mocks | jest APIs | vi APIs with migration differences to check |
Before switching, pick a test that uses your most involved mock, timer, or transform. Run it in both runners and check that it fails for the same reason when you introduce the bug it should catch. Keep Jest if the extra migration work outweighs reusing the app's Vite setup.
When to Choose
| Scenario | Pick |
|---|---|
| Unit and integration tests | Vitest |
| React component tests | Vitest + Testing Library |
| E2E tests | Playwright |
| Visual regression | Playwright + Chromatic |
| Existing Jest codebase | Keep Jest or pilot a Vitest migration |
| CI performance | Measure startup and suite time with your own tests |
| Cross-browser testing | Playwright projects when WebKit is required |
The Testing Culture Problem: Why Good Tooling Isn't Enough
The testing landscape in 2026 has excellent tooling. The bottleneck isn't tools — it's culture. Teams that have fast, well-chosen test stacks still ship bugs that well-placed tests would have caught, because the tests that would have caught those bugs don't exist. Understanding why test coverage is systematically low in specific areas helps teams improve their coverage where it matters most.
The coverage patterns that consistently fail: state management during error conditions, race conditions in async operations, and edge cases in data transformation. These are also the patterns that are hardest to test because they require setup of unusual states that don't occur in happy-path testing. The result is test suites with 85% line coverage that systematically miss the failure modes that cause production incidents. Line coverage is a poor proxy for test quality when the uncovered lines are the error-handling paths.
The Testing Library philosophy ("test what users see, not how it's implemented") addresses part of this — tests that verify accessible elements and user interactions survive refactors better than tests that verify internal React state. But even user-centric tests rarely cover: what does the UI show when an API returns a 500 error? What happens when the user's session expires mid-form? What if network requests arrive out of order? These scenarios require deliberate effort to test because they require simulating failure conditions.
The practical approach that works for teams: designate "incident tests" — after every production incident that a test could have caught, write the test before closing the incident. This produces tests that target real failure modes rather than hypothetical ones. Over 12 months, incident tests accumulate into a test suite that covers the specific edge cases that your production environment actually encounters. The coverage number may not improve substantially (incident tests often target rarely-executed paths), but production incident rates consistently decrease in teams that practice this discipline.
The second effective practice: require tests in code review for new features, but measure coverage by feature completion rather than line count. "This feature is not done until its happy path and top three error cases have tests" is more actionable than "maintain 80% line coverage." Engineers who understand what cases need testing write better tests than engineers who are optimizing for a coverage number.
The Component Testing Landscape
Use Vitest with Testing Library and jsdom or happy-dom to check how a React component responds to a click or what it exposes by role and name. These checks can run alongside your unit tests. If a menu must stay on screen when its container scrolls, run that test in a browser so the layout engine can position it. For that menu, add a story with a scrollable container to a gallery served by your dev server. In Playwright Test, pass the story ID to the built-in mount fixture, scroll the container, and check the menu’s position in the browser. Measure startup and suite time in your own CI before moving the rest of the suite. Playwright component testing
Testing Strategies That Actually Work at Scale
The testing pyramid (unit > integration > E2E) is still the conceptual model, but the specific ratios have shifted in 2026 based on what's proven effective:
- Unit tests (Vitest): best ROI for pure functions, data transformation utilities, business logic. A function that calculates package health scores from raw npm data is a perfect unit test target — deterministic input, deterministic output, no dependencies.
- Integration tests (Vitest + real DB): the 2026 consensus is that mocking databases was a mistake. Integration tests that hit a real (test) database with predictable seed data are more reliable than mocked database tests. Use a separate test database with Drizzle or Prisma's
$transactionrollback pattern to keep tests isolated. - Component tests (Vitest + Testing Library): focus on user interactions and accessibility, not component internals. The test should break when user-visible behavior changes, not when you refactor internal implementation.
- E2E tests (Playwright): focus on critical user journeys. Most teams run 20-50 E2E tests covering checkout, login, core features — not comprehensive coverage. Run on real browsers in CI, parallelize across 4-8 workers.
The antipattern to avoid: high E2E test counts with mocked external services. An E2E test that mocks your API server is testing your test harness, not your application. Keep E2E tests thin and running against real services where possible. The signal that an E2E test is over-mocked: if removing all your E2E mocks would cause more than 30% of your E2E tests to fail, your E2E tests are testing infrastructure rather than user behavior. The appropriate response is to move those tests to the integration layer (Vitest + real test database) where they belong.
CI/CD Integration: Fast Feedback in Practice
The testing stack is only as good as the CI feedback loop. In 2026, teams with optimized testing CI achieve 3-minute feedback on most PRs:
vitest run --reporter=githubproduces inline GitHub annotations on test failuresturbo test --filter=...[origin/main](for monorepos) only runs affected testsplaywright test --workers=8 --shard 1/4parallelizes E2E across 4 CI runners- Coverage upload to Codecov with
--coverage.enabledin vitest config
The most impactful optimization most teams haven't done: run unit tests before integration tests in CI. Fast Vitest tests complete in 30 seconds; if they fail, skip the 2-minute integration test run entirely. This "fail fast" pattern is trivially configurable in GitHub Actions with job dependencies and saves significant CI minutes over a week. A team with 50 PRs per day and an average 20% unit test failure rate saves 50 × 0.2 × 2 minutes = 20 CI minutes per day from this single optimization — roughly $30-60/month in GitHub Actions costs for a medium team, plus the faster feedback benefit for engineers whose tests fail. The GitHub Actions dependency (needs: [unit-tests] on the integration-tests job) implements this with zero code change to your test suite. The second most impactful optimization: cache node_modules and test snapshots between CI runs. Combined with Turborepo remote caching, a typical medium-scale project achieves more than 80% CI cache hit rate — meaning 8 out of 10 PRs run tests in under 90 seconds because most packages haven't changed. For teams investing in CI performance, the combination of Vitest (fast unit tests), affected detection (skip unchanged packages), remote cache (reuse previous results), and fail-fast ordering (unit before integration) typically produces a 4-5x improvement in overall CI throughput without any changes to the tests themselves.
Compare testing library package health on PkgPulse.
See also: Jest vs Vitest and AVA vs Jest, Testing Compared: Vitest vs Jest vs Playwright 2026.