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

Top comments (0)