moonshine
moonshine

Reputation: 859

Cannot read property '' of undefined Angular 4 - unit testing

i'm learning angular 4. My app work's well but know i would like to UnitTest my components. Here's what i've done :

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { Http,ConnectionBackend,BaseRequestOptions } from '@angular/http';
import {MockBackend} from '@angular/http/testing';

import {DxSchedulerModule, DxCheckBoxModule, DxSelectBoxModule} from 'devextreme-angular';

import { CalendrierComponent } from './calendrier.component';
import {CalendrierModule} from './calendrier.module';

import {Person} from '../models/persons.model'
import {PersonsService} from '../services/persons.services'

import {Appointment} from '../models/appointment.model'
import {AppointmentService} from '../services/appointment.service'

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

  let personService:PersonsService;
  let appointmentService:AppointmentService;


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CalendrierComponent],
      imports:[DxSchedulerModule, DxCheckBoxModule, DxSelectBoxModule],
      providers: [AppointmentService,
        PersonsService,
        MockBackend,
        BaseRequestOptions,
        { provide: Http,
          useFactory: (backend: ConnectionBackend,
                       defaultOptions: BaseRequestOptions) => {
                         return new Http(backend, defaultOptions);
                       }, deps: [MockBackend, BaseRequestOptions] },
      ],
      schemas:[NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

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

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

  it('should have a defined component', () => {
    expect(component).toBeDefined();
  });

  it('add30mnto should return an hour with 30min more', () => {
    expect(appointmentService.add30mnTo('2017-08-16T12:30:00.000Z')).toEqual('2017-08-16T13:00:00.000Z');
  });

and here is the service i would like to test :

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Rx';
import { Appointment } from '../models/appointment.model';
import {PersonsService} from './persons.services'

@Injectable()
export class AppointmentService {

private AppointmentUrlGet = 'http://localhost/v0/croissants';
private AppointmentUrlWrite = 'http://localhost/v0/croissant';


public handleError(error: any): Promise<any> {
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
}

  constructor(private http: Http, private personsService: PersonsService) {}


  add30mnTo(date : string){
    var initialdate = (this.datetotimestamp(date) + 1800) * 1000;
    var dateinit = new Date (initialdate)
    var result = dateinit.toISOString();
    return result;
  }
.
.
.
.
}

after having a lot of trouble(ConnectionBackend for example), i have this error : Cannot read property 'add30mnTo' of undefined.

I've already checked these topics : Jasmine angular unit test 'Cannot read 'property' of undefined Angular 2 Unit Testing - Cannot read property 'root' of undefined

but theses solutions don't work for me... Did anyone have an idea of what i've did wrong ? Thanks !!

Upvotes: 1

Views: 5691

Answers (1)

Corey
Corey

Reputation: 5818

In this case, appointmentService is never defined or created. Simply declaring the variable let appointmentService:AppointmentService; does not instantiate it. You could try injecting the service rather than create an instance:

// Add too imports :
import { inject } from '@angular/core/testing';

//... In your describe function :
it('add30mnto should return an hour with 30min more', inject([AppointmentService], (appointmentService:AppointmentService) => {
  expect(appointmentService.add30mnTo('2017-08-16T12:30:00.000Z')).toEqual('2017-08-16T13:00:00.000Z');
}));

Upvotes: 1

Related Questions