🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Project 29: E-commerce Cart

Angular Engineer

Builds on these lessons

Component Task

Objective

TestBed.inject() retrieves a real service instance from the testing injector — the same way a component would get it, letting you test service logic in isolation.

You're building a shopping cart service, with a test for it.

Task: write a CartService with addItem and getCount, and a spec that injects it, adds one item, and asserts the count.

component.ts
import { Injectable } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Injectable({ providedIn: 'root' }) export class CartService { private items: string[] = []; addItem(name: string) { this.items.push(name); } getCount() { return this.items.length; } } describe('CartService', () => { it('should track added items', () => { TestBed.configureTestingModule({}); const service = TestBed.inject(CartService); service.addItem('Sneakers'); expect(service.getCount()).toBe(1); }); });

* Hint: Correct characters turn green, incorrect ones turn red.

Compiler Output
🅰️

Compile your component to see the result