Project: Tests
Prove it works.
The shop works when we click through it. Tests prove it keeps working, every time we change something.
- It works today
- Keep it working
- Tests
basket.spec.ts
Two sample books are shared by the tests. Before each test, we get a fresh basket. The first test checks the total. The second removes the first item, and checks that only Emma is left.
import { TestBed } from '@angular/core/testing';
import { Basket } from './basket';
const dune = { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99 };
const emma = { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99 };
describe('Basket', () => {
let basket: Basket;
beforeEach(() => basket = TestBed.inject(Basket));
it('totals the prices', () => {
basket.add(dune); basket.add(emma);
expect(basket.total()).toBeCloseTo(16.98);
});
it('removes one item by position', () => {
basket.add(dune); basket.add(emma); basket.remove(0);
expect(basket.items().map(b => b.title)).toEqual(['Emma']);
});
});Testing the whole project
The checkout test puts Dune in the basket. It creates the checkout, sets the form's model, and places the order. Then it checks the thank you message, and that the basket is empty. Run it. Ng test ran both spec files. All three tests passed.
import { TestBed } from '@angular/core/testing';
import { Checkout } from './checkout';
import { Basket } from './basket';
describe('Checkout', () => {
it('thanks the customer and empties the basket', async () => {
const basket = TestBed.inject(Basket);
basket.add({ id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99 });
const fixture = TestBed.createComponent(Checkout);
fixture.componentInstance.model.set({ name: 'Sam', email: 'sam@example.com' });
fixture.componentInstance.order();
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Thanks, Sam! You paid £9.99.');
expect(basket.count()).toBe(0);
});
}); ✓ basket.spec.ts > Basket > totals the prices
✓ basket.spec.ts > Basket > removes one item by position
✓ checkout.spec.ts > Checkout > thanks the customer and empties the basket
Test Files 2 passed (2)
Tests 3 passed (3)Also uses book.ts
export interface Book {
id: number;
title: string;
author: string;
price: number;
}Also uses basket.ts
import { Service, signal, computed } from '@angular/core';
import { Book } from './book';
@Service()
export class Basket {
private readonly list = signal<Book[]>([]);
readonly items = this.list.asReadonly();
readonly count = computed(() => this.list().length);
readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));
add(book: Book) { this.list.update(l => [...l, book]); }
remove(index: number) { this.list.update(l => l.filter((_, i) => i !== index)); }
clear() { this.list.set([]); }
}Also uses app.routes.ts
import { Routes } from '@angular/router';
import { BookList } from './book-list';
export const routes: Routes = [
{ path: '', redirectTo: 'books', pathMatch: 'full' },
{ path: 'books', component: BookList },
{ path: 'books/:id', loadComponent: () => import('./book-page').then(m => m.BookPage) },
{ path: 'basket', loadComponent: () => import('./basket-page').then(m => m.BasketPage) },
{ path: 'checkout', loadComponent: () => import('./checkout').then(m => m.Checkout) },
{ path: '**', redirectTo: 'books' },
];Also uses app.ts
import { Component, inject } from '@angular/core';
import { RouterOutlet, RouterLink } from '@angular/router';
import { Basket } from './basket';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink],
template: `
<nav class="bar">
<a id="home" routerLink="/books"><b>Page Turners</b></a>
<a id="cart" routerLink="/basket">Basket ({{ basket.count() }})</a>
</nav>
<router-outlet />
`,
styles: `.bar { display: flex; justify-content: space-between; margin-bottom: 8px; }`,
})
export class App {
basket = inject(Basket);
}Also uses book-list.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { RouterLink } from '@angular/router';
import { Book } from './book';
@Component({
selector: 'app-book-list',
imports: [RouterLink],
template: `
<input (input)="q.set($any($event.target).value)" placeholder="Search books">
@for (b of books.value(); track b.id) {
<p><a [routerLink]="['/books', b.id]">{{ b.title }}</a> · £{{ b.price }}</p>
} @empty { <p class="muted">No books found.</p> }
`,
})
export class BookList {
q = signal('');
books = httpResource<Book[]>(() => `/api/books?q=${this.q()}`, { defaultValue: [] });
}Also uses book-page.ts
import { Component, inject, input } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Basket } from './basket';
import { Book } from './book';
@Component({
selector: 'app-book-page',
template: `
@if (book.error()) { <p class="error">Book not found.</p> }
@else if (book.value(); as b) {
<h2>{{ b.title }}</h2>
<p>by {{ b.author }} · £{{ b.price }} <button (click)="basket.add(b)">Add</button></p>
}
`,
})
export class BookPage {
basket = inject(Basket);
id = input.required<string>();
book = httpResource<Book>(() => `/api/books/${this.id()}`);
}Also uses basket-page.ts
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Basket } from './basket';
@Component({
selector: 'app-basket-page',
imports: [RouterLink],
template: `
<h2>Your basket</h2>
@for (b of basket.items(); track $index) {
<p>{{ b.title }} · £{{ b.price }}
<button (click)="basket.remove($index)">×</button></p>
} @empty { <p>Your basket is empty.</p> }
<p><b>Total: £{{ basket.total().toFixed(2) }}</b></p>
@if (basket.count()) { <a id="checkout" routerLink="/checkout">Go to checkout</a> }
`,
})
export class BasketPage {
basket = inject(Basket);
}Also uses checkout.ts
import { Component, inject, signal } from '@angular/core';
import { form, FormField, required, email } from '@angular/forms/signals';
import { Basket } from './basket';
@Component({
selector: 'app-checkout', imports: [FormField], templateUrl: './checkout.html',
})
export class Checkout {
basket = inject(Basket);
done = signal('');
model = signal({ name: '', email: '' });
checkout = form(this.model, p => {
required(p.name); required(p.email); email(p.email);
});
order() {
const paid = this.basket.total().toFixed(2);
this.done.set(`Thanks, ${this.model().name}! You paid £${paid}.`);
this.basket.clear();
}
}Also uses checkout.html
<h2>Checkout</h2>
@if (done()) {
<p class="card">{{ done() }}</p>
} @else {
<input [formField]="checkout.name" placeholder="Name">
<input [formField]="checkout.email" placeholder="Email">
<p>To pay: £{{ basket.total().toFixed(2) }}</p>
<button [disabled]="checkout().invalid()" (click)="order()">Place order</button>
}Also uses basket.spec.ts
import { TestBed } from '@angular/core/testing';
import { Basket } from './basket';
const dune = { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99 };
const emma = { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99 };
describe('Basket', () => {
let basket: Basket;
beforeEach(() => basket = TestBed.inject(Basket));
it('totals the prices', () => {
basket.add(dune); basket.add(emma);
expect(basket.total()).toBeCloseTo(16.98);
});
it('removes one item by position', () => {
basket.add(dune); basket.add(emma); basket.remove(0);
expect(basket.items().map(b => b.title)).toEqual(['Emma']);
});
});Also uses _mode
testWhat the project used
Routes, and lazy loading, for the pages. HTTP resource, for the books. A service, with signals, for the basket. A signal form, for checkout. And tests, for the logic.
| key | value |
|---|---|
| Routing | pages, parameters, lazy |
| httpResource | books from the API |
| @Service + signals | the basket |
| Signal forms + tests | checkout, proof |
Summary
Tests for the basket, and checkout, prove the shop works, and keep it working. The project is done. Next, where to go from here.
Key takeaways- basket.spec.ts
- checkout.spec.ts
- 3 tests passed