# 12. Test EventService

## 1. Fix broken tests with injected dependencies

* Add the fake EventService and HttpClient to the EventComponent.

{% code title="src/app/event/event.component.spec.ts" %}

```typescript
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();
  });
});
```

{% endcode %}

## 2. Fix EventService tests

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

{% code title="src/app/event/event.service.spec.ts" %}

```typescript
import { TestBed, inject } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';

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

describe('EventService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [EventService]
    });
  });

  it('should be created', inject([EventService], (service: EventService) => {
    expect(service).toBeTruthy();
  }));
});
```

{% endcode %}

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

* Add fake service and spy on it.

{% code title="src/app/event/container/event/event.component.spec.ts" %}

```typescript
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 { of } from 'rxjs';

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

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

  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;
    service = TestBed.get(EventService);
    fixture.detectChanges();
  });

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

  it('should have a list of attendees set', () => {
    const fakeAttendees = [{ name: 'FAKE_NAME', attending: false, guests: 0 }];

    jest
      .spyOn(service, 'getAttendees')
      .mockImplementation(() => of(fakeAttendees));

    component.ngOnInit();

    component.attendees$.subscribe(attendees => {
      expect(attendees).toEqual(fakeAttendees);
    });
  });
});
```

{% endcode %}

## StackBlitz Link

{% embed url="<https://stackblitz.com/github/duncanhunter/angular-and-ngrx-demo-app/tree/12-test-event-service>" %}
Web Link: Link to the demo app running in StackBlitz
{% endembed %}

## Extras and Homework <a href="#extras-and-homework" id="extras-and-homework"></a>

{% hint style="danger" %}
These extra sections are for doing after the course or if you finish a section early. Please move onto the next section if doing this as a workshop when the instructor advises.

WARNING: Some of these extra sections will make it more difficult to copy and paste the code examples later on in the course.

You might need to apply the code snippet examples a little more carefully amongst any "extras section" code you may add. If you are up for some extra challenges these sections are for you.
{% endhint %}

### Add EventService tests <a href="#convert-the-homecomponent-into-a-feature-module" id="convert-the-homecomponent-into-a-feature-module"></a>

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.

{% code title="src/app/event/services/event/event.service.spec.ts" %}

```typescript
import { TestBed, inject } from '@angular/core/testing';
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';

import { Attendee } from '../../../models';
import { EventService } from './event.service';

describe('EventService', () => {
  let httpTestingController: HttpTestingController;
  let eventService: EventService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [EventService]
    });

    eventService = TestBed.get(EventService);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('should be created', inject([EventService], (service: EventService) => {
    expect(service).toBeTruthy();
  }));

  it('can test HttpClient.get attendees', () => {
    const testAttendees: Attendee[] = [
      {
        name: 'Test Data',
        attending: true,
        guests: 1
      }
    ];

    eventService.getAttendees().subscribe();

    const req = httpTestingController.expectOne('/api/attendees');

    expect(req.request.method).toEqual('GET');

    req.flush(testAttendees);

    httpTestingController.verify();
  });
});

```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://duncanhunter.gitbook.io/angular-and-ngrx/12.-test-eventservice.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
