Sub topic 14
Running tests in a real browser
This chapter assumes you can already run ng test, write a TestBed test, and read the test target in angular.json. It covers why you might move your Vitest tests out of the default simulated DOM and into a real browser, how to do that with the Angular CLI, and what changes.
Where your tests run by default
With the unit-test builder and the Vitest runner, ng test runs your specs in Node.js. Node has no DOM, so the runner supplies a simulated one. The usual choice is jsdom, a JavaScript implementation of the DOM that Vitest can use as its environment. Your components render into jsdom's document, and fixture.nativeElement is a jsdom element.
This is fast and needs no browser installed. It works for most component tests: rendering text, clicking buttons, reading inputs and outputs, and mocking services. But jsdom is not a browser. It parses HTML and CSS and implements much of the DOM API, but it has no layout engine and no rendering. Anything that depends on how the browser actually draws the page is either missing or returns placeholder values.
What jsdom cannot tell you
| Behavior | In jsdom | In a real browser |
|---|---|---|
| `getBoundingClientRect()`, `offsetWidth`, `scrollHeight` | Zeros | Real pixel values |
| Layout from CSS (flex, grid, media queries) | Not computed | Computed by the engine |
| `IntersectionObserver`, `ResizeObserver` | Missing or stubbed | Native behavior |
| Real focus and keyboard behavior, such as tab order | Partial | Native behavior |
| Browser-specific quirks (Chromium vs Firefox vs WebKit) | Not represented | Reproduced when you run that browser |
If your component computes something from layout, such as a virtual scroller, a tooltip positioned next to its anchor, or a sticky header, a jsdom test can pass while the feature is broken. A real-browser run closes that gap.
The cost is speed and setup. A browser must be installed, startup takes longer, and CI needs the browser binaries. For that reason, browser mode is usually an addition to the jsdom run, not a replacement for it.
Installing a browser provider
Vitest talks to a real browser through a browser provider package. The Angular CLI does not bundle one. You install the provider you want, plus the tool it drives.
The most common choice is Playwright, which can download and manage Chromium, Firefox, and WebKit:
npm install --save-dev vitest playwright @vitest/browser-playwrightOther providers exist, such as WebdriverIO (@vitest/browser-webdriverio) and a preview provider for quick local use. Check the Angular and Vitest documentation for the provider names that match the versions you use, because these package names have changed between releases.
If Playwright has not yet downloaded browsers on your machine, install them once:
npx playwright install chromiumChoosing a browser with ng test
You select browsers with the --browsers option. The names are the browser engines the provider supports, for example chromium, firefox, or webkit with Playwright.
ng test --browsers=chromiumOnce you pass --browsers, the CLI stops using jsdom for that run. The same spec files are loaded into a page in the browser, and Vitest reports the results in your terminal as before.
You can also set it in angular.json so ng test always uses a browser. This extends the test target you saw in the setup chapter:
{
"test": {
"builder": "@angular/build:unit-test",
"options": {
"runner": "vitest",
"browsers": ["chromium"]
}
}
}A command-line flag overrides the value in angular.json. A practical setup keeps the default as jsdom for the fast loop and uses a named configuration for the browser run. For example, add a browser entry under the target's configurations, then run ng test --configuration=browser. Adding that entry is a standard angular.json change and does not need any new test code.
Headless and headed runs
A headed run opens a visible browser window, which helps while you debug. A headless run uses no window and is what you want on a build server.
Headless mode is turned on automatically when the CI environment variable is set. Locally you can request it by adding the Headless suffix to the browser name:
ng test --browsers=ChromiumHeadlessRunning more than one browser
browsers takes a list, so you can run the same specs in several engines:
ng test --browsers=chromium,firefoxThis is where real-browser mode pays off beyond layout. A bug in how Firefox handles a form control, for example, only shows up when a Firefox instance runs the test. Each extra browser multiplies run time, so most teams use one browser for every commit and the full set on a schedule or before release.
A test that only makes sense in a browser
This component sets a fixed size through CSS. The test reads the size back from the layout engine.
import { Component } from '@angular/core';
@Component({
selector: 'app-panel',
template: `<div class="panel" data-testid="panel">Panel</div>`,
styles: `
.panel {
width: 200px;
height: 40px;
padding: 8px;
box-sizing: border-box;
}
`,
})
export class PanelComponent {}import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { PanelComponent } from './panel.component';
describe('PanelComponent layout', () => {
it('renders the panel at the size set in CSS', () => {
const fixture = TestBed.createComponent(PanelComponent);
fixture.detectChanges();
const panel: HTMLElement = fixture.nativeElement.querySelector(
'[data-testid="panel"]',
);
const box = panel.getBoundingClientRect();
expect(box.width).toBe(200);
expect(box.height).toBe(40);
});
});Run ng test with the default jsdom environment and this test fails, because getBoundingClientRect() returns zeros there. Run ng test --browsers=chromium and it passes, because Chromium lays the element out. Nothing in the test code changed. Only the environment did.
The describe, it, expect, and vi APIs from earlier chapters behave the same in browser mode. TestBed, fixtures, detectChanges, providers, HttpTestingController, and fake timers are the same too, because they belong to Angular and Vitest, not to the DOM implementation.
Differences to expect
Most existing specs run unchanged, but a few things behave differently once a real browser is involved.
- Real layout and CSS apply. An element hidden by
display: nonehas no size, and:hoveror media-query rules take effect. A test that relied on jsdom ignoring styles can start failing. - Test pages are real pages. State such as
localStorage, cookies, and focus belongs to a real browser context. Clear what you write inafterEachso one test does not leak into the next. - Failures can differ by engine. If a test passes in Chromium and fails in Firefox, the cause is usually a real difference in the browser, not a flaky test.
- Startup is slower. The first run launches a browser process. Expect seconds of overhead per run, not milliseconds.
- Debugging is better. In a headed run you can open the browser's developer tools, set breakpoints, and inspect the rendered component.
Deciding when to use browser mode
Use these criteria to decide which tests need a browser.
- The behavior depends on measurements. Sizes, positions, scrolling, and overflow need a layout engine.
- The behavior depends on browser APIs jsdom lacks. Observers, native form validation UI, and clipboard access are examples.
- A bug only reproduced in one browser. Add a regression test and run it in that engine.
- The test is about data flow, templates, or services. Keep it in jsdom. Browser mode adds cost and no information.
A workable split is this. Run the whole suite in jsdom on every save. Run the full suite in a headless browser in CI, where the extra time is cheap and the result gates the merge.
Exercise
A component test checks that a dropdown menu appears directly below its button by comparing getBoundingClientRect() values. It passes with ng test in the default environment, then fails with a message about expected values when you run ng test --browsers=chromium. Which result should you trust, and why?
Show answer
Trust the Chromium run. In jsdom, getBoundingClientRect() returns zeros, so two elements always look aligned and the assertion passes without proving anything. A real browser computes actual layout, so the failure shows a real positioning problem (or a wrong expectation in the test) that you should investigate.
Exercise
Write the ng test command that runs your suite headless in Chromium and Firefox, and say which environment variable makes headless mode the default without a suffix.
Show answer
ng test --browsers=ChromiumHeadless,FirefoxHeadless. Headless mode is also enabled automatically when the CI environment variable is set.