12. Test EventService

In this section we will fix the now broken spec files missing newly injected dependencies in the components and services under test.

1. Fix broken tests with injected dependencies

  • Add the fake EventService and HttpClient to the EventComponent.

src/app/event/event.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { EventComponent } from './event.component';
import { NO_ERRORS_SCHEMA } from '@angular/compiler/src/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';

import { EventService } from '../../services/event.service';

describe('EventComponent', () => {
  let component: EventComponent;
  let fixture: ComponentFixture<EventComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: HttpClient, useValue: null },
        {
          provide: EventService,
          useValue: {
            getAttendees: () => {}
          }
        }
      ],
      declarations: [EventComponent],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EventComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

2. Fix EventService tests

  • Fix missing injected HttpClient in EventService by using Angular's HttpClientTestingModule.

3. Add a spy to pass in fake attendees to mock the service

  • Add fake service and spy on it.

Web Link: Link to the demo app running in StackBlitz

Extras and Homework

Add EventService tests

We have no test coverage on our EventService yet. You can read more about how to use Angular's approach to testing HTTP here https://angular.io/guide/http#testing-http-requests.

Steps:

  1. Provide and inject EventService into test.

  2. Make fake attendees array.

  3. Call services getAttendees method and do not forget to subscribe!

  4. Check the path was called.

  5. Verify there are no outstanding requests.

Last updated