AI Hints
Home›Angular Tutorial›Testing a Service, Testing User Actions and Practice: Test the Basket
Angular · Lesson 108 of 120

Practice: Test the Basket

Your turn.

⏱ 2 min read▶ Video at 2:09:40🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's practise testing. You'll write a test for the basket's clear method.

  • Test the basket
  • The clear method
  • Your turn

Test clear()

Your turn. Pause the video, and try this. Write a test that adds two books to the basket, clears it, and checks that the count, and total, are both zero. Here is one solution. The test gets a basket, and adds two books. Then it clears it, and checks both signals. The test passed.

✍️ Exercise: Test clear()

In basket.spec.ts: get a Basket with TestBed.inject, add two books, call clear(), then expect count() and total() to be 0.

Show hint

const basket = TestBed.inject(Basket);

Show solution
basket.spec.tstypescript
import { TestBed } from '@angular/core/testing';
import { Basket } from './basket';

describe('Basket', () => {
  it('clear() empties it', () => {
    const basket = TestBed.inject(Basket);
    basket.add({ title: 'Dune', price: 9.99 });
    basket.add({ title: 'Circe', price: 10.99 });
    basket.clear();
    expect(basket.count()).toBe(0);
    expect(basket.total()).toBe(0);
  });
});
Output
 ✓ basket.spec.ts > Basket > clear() empties it
 Test Files  1 passed (1)
      Tests  1 passed (1)

What module twelve taught

RxJS makes, and transforms, streams of values. Debounce time, and switch map, make a good search. To signal brings observables into signals. And tests check components, services, and user actions, with ng test.

keyvalue
of, from, Subjectmake streams
map, filter, debounceTimetransform them
toSignal()into signals
ng testcheck it all

Summary

You can now work with streams, and test your app. That's the end of module twelve. Next, the final module. Production, and a project.

Key takeaways
  • RxJS
  • toSignal()
  • Testing
Next up: Building for Production — ready for real users