Modern Automated QA in Angular: Vitest & Playwright
A Modern Testing Stack: Trade outdated runners for Vitest to run lightning-fast component tests, and pair it with Playwright for end-to-end coverage.
Legacy Angular testing relied heavily on Karma (a runner that spawned full, memory-hungry headless Chrome instances for every test run) and Jasmine (an aging assertion engine). Together, they produced sluggish test execution, intermittent local flakiness, heavy CI resource consumption, and technical debt—culminating in Karma's official deprecation by the Angular team.
Modern Angular revamps automated quality assurance by splitting test execution into two high-velocity layers:
- **Unit & Component Testing with Vitest:** Executes directly in Node.js using Vite’s compilation pipeline and lightweight simulated DOM environments (happy-dom or jsdom). It provides instant feedback, native ESM support, multi-threaded worker pools, and zero compilation overhead.
- **End-to-End (E2E) Testing with Playwright:** Automates real Chromium, Firefox, and WebKit engines with built-in auto-waiting, network mocking, and resilient user-centric locators.
## 1. Legacy Stack vs. Modern Tooling
| Testing Concern | Legacy Stack (Karma + Jasmine + Protractor) | Modern Stack (Vitest + Playwright) |
| --- | --- | --- |
| Runner Engine | Karma (spins up full Chrome browser instances) | Vitest (Vite-driven multi-threaded worker pool) |
| Execution Speed | Minutes for medium-to-large suites | Milliseconds to seconds (sub-second watch mode) |
| DOM Runtime | Heavy browser instance required for small tests | In-memory simulated DOM (happy-dom or jsdom) |
| Watch Mode | Sluggish full rebuilds via Webpack | Instant, surgical re-runs powered by Vite's module graph |
| E2E Tool | Protractor (deprecated, brittle browser.sleep() calls) | Playwright (native CDP/WebDriver BiDi, auto-waiting) |
| Cross-Browser Setup | Rigid, version-locked Selenium WebDriver installs | Hermetic browser binaries (Chromium, Firefox, WebKit) |
## 2. Unit & Component Testing with Vitest
Vitest matches the familiar Jest API (describe, it, expect, vi.fn()) while compiling directly on Vite—bypassing heavy Webpack compilation steps.
### 2.1 Configuring Vitest (vite.config.ts)
```ts
// vite.config.ts
import { defineConfig } from 'vite';
import angular from '@analogjs/vite-plugin-angular';
export default defineConfig({
plugins: [angular()],
test: {
globals: true,
environment: 'happy-dom', // Lightweight in-memory DOM
setupFiles: ['src/test-setup.ts'],
include: ['src/**/*.spec.ts'],
reporters: ['default'],
},
});
```
```ts
// src/test-setup.ts
import '@analogjs/vite-plugin-angular/setup-snapshots';
import { TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
// Initialize Angular testing environment once
TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
```
### 2.2 Writing a High-Performance Component Spec
Here is an interactive cart item component using Signals, input(), output(), and computed expressions:
### The Component Under Test
```ts
// src/app/cart/cart-item.component.ts
import { Component, input, output, computed } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
export interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
@Component({
selector: 'app-cart-item',
standalone: true,
imports: [CurrencyPipe],
template: `
();
quantityChange = output<{ id: string; quantity: number }>();
removed = output();
subtotal = computed(() => this.item().price * this.item().quantity);
increaseQty(): void {
this.quantityChange.emit({ id: this.item().id, quantity: this.item().quantity + 1 });
}
decreaseQty(): void {
if (this.item().quantity > 1) {
this.quantityChange.emit({ id: this.item().id, quantity: this.item().quantity - 1 });
}
}
}
```
### The Vitest Spec (cart-item.component.spec.ts)
```ts
// src/app/cart/cart-item.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ComponentRef } from '@angular/core';
import { CartItemComponent, CartItem } from './cart-item.component';
describe('CartItemComponent (Vitest)', () => {
let fixture: ComponentFixture;
let component: CartItemComponent;
let componentRef: ComponentRef;
const mockItem: CartItem = {
id: 'prod-101',
name: 'Mechanical Keyboard',
price: 120,
quantity: 2
};
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CartItemComponent]
}).compileComponents();
fixture = TestBed.createComponent(CartItemComponent);
component = fixture.componentInstance;
componentRef = fixture.componentRef;
// Set signal inputs using the modern setInput() test utility
componentRef.setInput('item', mockItem);
fixture.detectChanges();
});
it('should render item details and compute subtotal correctly', () => {
const el = fixture.nativeElement as HTMLElement;
const nameEl = el.querySelector('.name');
const subtotalEl = el.querySelector('[data-testid="subtotal"]');
expect(nameEl?.textContent).toContain('Mechanical Keyboard');
expect(subtotalEl?.textContent).toContain('$240.00'); // 120 * 2
});
it('should emit quantityChange with incremented value on button click', () => {
// Spy on functional output
const emitSpy = vi.fn();
component.quantityChange.subscribe(emitSpy);
const incrementBtn = fixture.nativeElement.querySelector('[data-testid="increment-btn"]') as HTMLButtonElement;
incrementBtn.click();
expect(emitSpy).toHaveBeenCalledWith({ id: 'prod-101', quantity: 3 });
});
it('should emit removed event with product ID', () => {
const removeSpy = vi.fn();
component.removed.subscribe(removeSpy);
const removeBtn = fixture.nativeElement.querySelector('[data-testid="remove-btn"]') as HTMLButtonElement;
removeBtn.click();
expect(removeSpy).toHaveBeenCalledWith('prod-101');
});
it('should update subtotal when signal input changes', () => {
// Update signal input dynamically
componentRef.setInput('item', { ...mockItem, quantity: 4 });
fixture.detectChanges();
const subtotalEl = fixture.nativeElement.querySelector('[data-testid="subtotal"]');
expect(subtotalEl?.textContent).toContain('$480.00'); // 120 * 4
});
});
```
## 3. End-to-End (E2E) Testing with Playwright
Vitest isolates components and services in synthetic environments, while Playwright verifies full application journeys inside actual rendering engines.
### 3.1 Why Playwright Outperforms Legacy Tools
- **Built-in Auto-Waiting:** Playwright automatically waits for elements to be actionable (visible, stable, interactable) before firing clicks or keystrokes—eliminating artificial sleep() statements.
- **Network Interception:** Intercept, modify, or mock API responses at the network boundary to test edge conditions (e.g., HTTP 500 crashes, network dropouts) without touching application logic.
- **Trace Viewer:** Capture video recordings, DOM snapshots, console logs, and network timelines for failing CI runs.
### 3.2 Setting Up Playwright (playwright.config.ts)
```ts
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env['CI'],
retries: process.env['CI'] ? 2 : 0,
workers: process.env['CI'] ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost:4200',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'Chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'Firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'WebKit (Safari)', use: { ...devices['Desktop Safari'] } },
{ name: 'Mobile Safari', use: { ...devices['iPhone 14'] } }
],
webServer: {
command: 'npm run start',
url: 'http://localhost:4200',
reuseExistingServer: !process.env['CI'],
timeout: 120000,
},
});
```
### 3.3 Writing an Enterprise E2E Test (e2e/checkout-flow.spec.ts)
```ts
// e2e/checkout-flow.spec.ts
import { test, expect } from '@playwright/test';
test.describe('E-Commerce Checkout Flow', () => {
test.beforeEach(async ({ page }) => {
// 1. Mock inventory backend to isolate frontend tests
await page.route('**/api/inventory', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 'item-1', name: 'Ergonomic Desk Chair', price: 299, stock: 5 },
{ id: 'item-2', name: '4K IPS Monitor', price: 450, stock: 2 }
])
});
});
await page.goto('/shop');
});
it('completes order placement with correct subtotal calculation', async ({ page }) => {
// 2. Locate elements using resilient, accessible selectors
const chairCard = page.locator('.product-card', { hasText: 'Ergonomic Desk Chair' });
const addToCartBtn = chairCard.getByRole('button', { name: /add to cart/i });
await addToCartBtn.click();
// Verify cart badge reflects update
const cartBadge = page.getByTestId('cart-badge-count');
await expect(cartBadge).toHaveText('1');
// Proceed to checkout view
await page.getByRole('link', { name: /view cart/i }).click();
await expect(page).toHaveURL(/\/checkout/);
// Verify order breakdown
await expect(page.getByRole('heading', { name: 'Order Summary' })).toBeVisible();
await expect(page.getByText('Ergonomic Desk Chair')).toBeVisible();
await expect(page.getByTestId('checkout-total')).toHaveText('$299.00');
// Fill checkout form
await page.getByLabel(/full name/i).fill('Alex Vance');
await page.getByLabel(/email address/i).fill('alex@enterprise.dev');
await page.getByLabel(/shipping address/i).fill('742 Evergreen Terrace');
// Stub order submission response
await page.route('**/api/orders', async (route) => {
await route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ orderId: 'ORD-98234', success: true })
});
});
// Confirm order
await page.getByRole('button', { name: /confirm order/i }).click();
// Verify confirmation redirect
await expect(page).toHaveURL(/\/order-confirmed/);
await expect(page.getByRole('heading', { name: /thank you for your order/i })).toBeVisible();
await expect(page.getByText('ORD-98234')).toBeVisible();
});
it('displays error banner when payment gateway rejects transaction', async ({ page }) => {
await page.goto('/checkout');
// Simulate 500 failure on payment API
await page.route('**/api/orders', async (route) => {
await route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({ error: 'Card processing unavailable.' })
});
});
await page.getByLabel(/full name/i).fill('Test User');
await page.getByLabel(/email address/i).fill('test@user.com');
await page.getByRole('button', { name: /confirm order/i }).click();
// Assert visible error alert
const errorBanner = page.getByRole('alert');
await expect(errorBanner).toBeVisible();
await expect(errorBanner).toContainText('Card processing unavailable.');
});
});
```
```text
4. Modern Testing Distribution
┌───────────────────┐
│ PLAYWRIGHT │ ~10% (End-to-End User Journeys)
│ Real Browsers │ Multi-page flows, critical API mocks,
│ Cross-Browser │ accessibility, and visual regression
└─────────┬─────────┘
│
┌──────────────────┴──────────────────┐
│ VITEST │ ~30% (Component Integration)
│ Simulated DOM (happy-dom / jsdom) │ Signal inputs/outputs, template events,
│ Fast rendering passes │ control flow (@if, @for), CSS bindings
└──────────────────┬──────────────────┘
│
┌───────────────────────┴───────────────────────┐
│ VITEST │ ~60% (Unit & Core Logic)
│ Pure Node / Worker Execution │ SignalStores, computed logic,
│ Zero DOM overhead │ custom pipes, guards, interceptors
└───────────────────────────────────────────────┘
```
By offloading heavy browser setups to targeted E2E flows and handling unit/component logic in Vitest worker threads, you achieve fast feedback loops locally and dependable verification in CI.
{{ item().name }}
{{ item().price | currency }}
`
})
export class CartItemComponent {
item = input.required
{{ item().quantity }}
Subtotal: {{ subtotal() | currency }}
