lundi 27 novembre 2017

Karma Angular Testing - cannot call a method (that calls a Service) from component

I have a compoment (rooms.component) who calls a Service (RoomService).

In normal eviroment it works perfectly.

I can not test it using Karma. As you see I can the method from the component from Karma, but the test Fails saying that rooms[] is undefined

At the beginning I had Problem with the route (It called non existing Service localhost:karmaport/api.......)

I solved using a Proxy in the Karma conf, but, even if I do not get 404 NOT FOUND anymore, the Service seems not to work (the Array is undefined)

I hope you can help me.

rooms.component.ts

import { Component, OnInit }        from '@angular/core';

import { ActivatedRoute, ParamMap } from '@angular/router';
import { Location }                 from '@angular/common';

import { RoomService }              from '../services/room.service'
import { Room }                     from '../classes/room'

@Component({
  selector: 'rooms-component',
  templateUrl: './rooms.component.html',
  styleUrls: ['./rooms.component.css']
})
export class RoomsComponent implements OnInit {

  rooms: Room[];

  constructor(
      private roomService: RoomService,
      private route: ActivatedRoute,
      private location: Location
  ) { }

  ngOnInit() {
    this.getRooms();
  }

  getRooms(): void {
    this.roomService.getRooms().then(rooms => this.rooms = rooms);
  }

}

rooms.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { RoomsComponent } from './rooms.component';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule }          from '@angular/forms';
import { RoomService } from '../services/room.service';
import { TimetableService } from '../services/timetable.service';
import { RouterTestingModule } from '@angular/router/testing';


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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
            imports: [
        HttpModule,
        FormsModule,
        RouterTestingModule,
    ],
      declarations: [ RoomsComponent ],
      providers: [
    RoomService,
    TimetableService,
  ]
    })
    .compileComponents();
  }));

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

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

  it('should be greter than 0', () => {
    component.getRooms()
    expect(component.rooms.length).toBeGreatherThan(10);
  });
});

RoomService

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { City } from '../classes/city';
import { Building } from '../classes/building';
import { Room } from '../classes/room';
import { Lecture } from '../classes/lecture';
import { FreeRoom } from '../classes/free-room';
import { TimetableService } from './timetable.service';

@Injectable()
export class RoomService {

  private apiUrl = 'api';  // URL to web api
  private headers = new Headers({'Content-Type': 'application/json'});

  lectures: Lecture[];
  constructor(private http: Http, private tmtblServ: TimetableService) { }

  getCities(): Promise<City[]> {
    return this.http.get(`${this.apiUrl}/cities`)
             .toPromise()
             .then(response => response.json() as City[])
             .catch(this.handleError);
  }

  getBuildings(): Promise<Building[]> {
    return this.http.get(`${this.apiUrl}/buildings`)
             .toPromise()
             .then(response => response.json() as Building[])
             .catch(this.handleError);
  }

  getRooms(): Promise<Room[]> {
    return this.http.get(`${this.apiUrl}/rooms`)
             .toPromise()
             .then(response => response.json() as Room[])
             .catch(this.handleError);
  }

Aucun commentaire:

Enregistrer un commentaire