wasAsked.

can you explain stepwise how unit testing done in angular?

EY · Role not specified · technical

Published

Year not specified · Angular

Community answers

Posted by wasAsked editorial collection

Angular unit tests check components, services, pipes and directives in isolation. Projects created with the Angular CLI historically used Jasmine with the Karma runner; newer versions are moving to Vitest (and many teams use Jest). The steps are similar. Step 1 — Run the tests ng test runs every *.spec.ts file and watches for changes. In CI, run headless with a single run (for example ng test --watch=false --browsers=ChromeHeadless with Karma). Step 2 — Test services in isolation describe('PriceService', () => { it('applies discount', () => { const service = new PriceService(); expect(service.apply(100, 10)).toBe(90); }); }); Step 3 — Test services that call HTTP beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); it('loads products', () => { const service = TestBed.inject(ProductService); const http = TestBed.inject(HttpTestingController); service.getAll().subscribe(list => expect(list.length).toBe(1)); http.expectOne('/api/products?page=1').flush([{ id: 1, name: 'Pen', price: 10 }]); http.verify(); }); Step 4 — Test components with TestBed beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ProductListComponent], providers: [{ provide: ProductService, useValue: { getAll: () => of([{ id: 1, name: 'Pen', price: 10 }]) } }] }).compileComponents(); }); it('renders products', () => { const fixture = TestBed.createComponent(ProductListComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Pen'); }); Step 5 — Test interactions Trigger clicks on DOM elements, check emitted outputs, and use fakeAsync with tick() (or waitForAsync) for timers and async code. Good practices - Arrange-Act-Assert structure, one behaviour per test. - Mock dependencies (spies with jasmine.createSpyObj or vi.fn), never call real APIs. - Test behaviour visible to the user rather than private implementation details. - Measure coverage (ng test --code-coverage) and focus on business-critical logic. - Complement unit tests with end-to-end tests (Playwright or Cypress) for full user journeys.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics