Test bed creates a component, inside a test, and gives back a fixture. When stable waits until the page is up to date. Native element is the component's real HTML element. So we can find things in it, and check their text.
The first test creates the app, waits, finds the heading, and checks its text. The second checks the paragraph, for four books. Run it. Ng test ran both tests, and both passed.
app.spec.tstypescript
import { TestBed } from '@angular/core/testing';import { App } from './app';describe('App', () => { it('shows the shop name', async () => { const fixture = TestBed.createComponent(App); await fixture.whenStable(); const h1 = fixture.nativeElement.querySelector('h1'); expect(h1.textContent).toBe('Page Turners'); }); it('shows how many books are in stock', async () => { const fixture = TestBed.createComponent(App); await fixture.whenStable(); expect(fixture.nativeElement.querySelector('p').textContent).toContain('4 books'); });});
Output
✓ app.spec.ts > App > shows the shop name
✓ app.spec.ts > App > shows how many books are in stock
Test Files 1 passed (1)
Tests 2 passed (2)
Also uses app.ts
import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `<h1>Page Turners</h1><p>{{ books }} books in stock</p>`,})export class App { books = 4;}
What does a failure look like? Here, the test expects page turner, without the s. Run it. The test failed. Vitest shows what it expected, and what it got. So we know exactly what's wrong.
app.spec.tstypescript
import { TestBed } from '@angular/core/testing';import { App } from './app';describe('App', () => { it('shows the shop name', async () => { const fixture = TestBed.createComponent(App); await fixture.whenStable(); const h1 = fixture.nativeElement.querySelector('h1'); expect(h1.textContent).toBe('Page Turner'); }); it('shows how many books are in stock', async () => { const fixture = TestBed.createComponent(App); await fixture.whenStable(); expect(fixture.nativeElement.querySelector('p').textContent).toContain('4 books'); });});
Output
× app.spec.ts > App > shows the shop name
→ expected 'Page Turners' to be 'Page Turner' // Object.is equality
✓ app.spec.ts > App > shows how many books are in stock
Test Files 1 failed (1)
Tests 1 failed | 1 passed (2)
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
FAIL app.spec.ts > App > shows the shop name
AssertionError: expected 'Page Turners' to be 'Page Turner' // Object.is equality
Expected: "Page Turner"
Received: "Page Turners"
❯ app.spec.ts:9:28
7| await fixture.whenStable();
8| const h1 = fixture.nativeElement.querySelector('h1');
9| expect(h1.textContent).toBe('Page Turner');
| ^
10| });
Also uses app.ts
import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `<h1>Page Turners</h1><p>{{ books }} books in stock</p>`,})export class App { books = 4;}