1

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 !!

3
  • It may come from this line expect(appointmentService.add30mnTo('2017-08-16T12:30:00.000Z')).toEqual('2017-08-16T13:00:00.000Z'); }); It mean that appointmentService is undefined Commented Aug 22, 2017 at 14:30
  • this was on of my thought, but i've define apointmentService on my spec ts... import {AppointmentService} from '../services/appointment.service' and i've added this line 'let appointmentService:AppointmentService;' on the describe part... i've made mimetism on what it was generated by the CLI for the component... Commented Aug 22, 2017 at 14:33
  • You may need to initialize your appointmentService variable with new operator Commented Aug 22, 2017 at 14:39

1 Answer 1

1

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');
}));
Sign up to request clarification or add additional context in comments.

2 Comments

it works thanks ! Did you have an idea of how can i interact with component's method ? when i did component.toggleMonth() for example, it didn't work. i have stricly the same errors ...
If your previous tests are passing, then component should be defined. It's not enough information to know for sure. Perhaps open another question with the test and the component method toggleMonth included.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.