DEV Community

code-js in
code-js in

Posted on

Understanding Unit Testing in Angular: Mocked Service API Calls and Component Rendering

Imagine you have an Angular component, AppComponent, which displays product information fetched from a service, AppService. We want to write a unit test to ensure that AppComponent correctly renders the product title.

Here’s the unit test code we’ll be examining:

import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
import { of } from 'rxjs/internal/observable/of';

describe('AppComponent', () => {

  beforeEach( () => {
    TestBed.configureTestingModule({
      imports: [AppComponent],
      providers: [AppService],
    }).compileComponents();
  });

  it('should render with mocked title', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const service = fixture.debugElement.injector.get(AppService);
    let mockData = {
      id: 1,
      title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptop',
      price: 109.95,
      description:
        'Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday',
      category: "women's clothing",
      image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg',
      rating: { rate: 3.9, count: 120 },
    };

    spyOn(service, 'getData').and.returnValue(of(mockData));

    fixture.detectChanges();
    const compiled = fixture.nativeElement as HTMLElement;
    expect(compiled.querySelector('h1')?.textContent).toContain('Hello, Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptop');

  });


});

Enter fullscreen mode Exit fullscreen mode

for more details please visit this blog -- Understanding Unit Testing in Angular: Mocked Service API Calls and Component Rendering

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more