Angular Unit Testing : Cannot read property 'findIndex' of undefined

时间:2017-08-04 12:30:57

标签: angular unit-testing typescript jasmine karma-jasmine

Am implementing an unit test for my Component .

i imported everything necessary : services , RouterModuleTesting ,FormsModule HttpModule ...

but i still confronting a strange error :

My Test file :

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CustomerDetailComponent } from './customer-detail.component';

import {DxProgressBarModule} from 'devextreme-angular';
import {RouterTestingModule} from '@angular/router/testing';

import { CustomerService } from './../customer.service';
import {HttpService} from '../../../shared/service/http.service';

import {HttpModule} from '@angular/http';
import {FormsModule} from '@angular/forms';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpModule,
        FormsModule,
        DxProgressBarModule,
        RouterTestingModule,
      ],
      providers:    [ CustomerService , HttpService ],
      declarations: [ CustomerDetailComponent ]
    })
    .compileComponents();
  }));

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

  it('Customer-detail component should be well defined', () => {
    expect(component).toBeDefined();
  });
});

My component.ts

import { Component, OnInit } from '@angular/core';
import { Response, Http } from '@angular/Http';
import { Router, ActivatedRoute, Params } from '@angular/router';

import { HttpService } from './../../../shared/service';
import { Customer } from './../../../model';
import { CustomerService } from './../customer.service';

@Component({
    selector: 'app-customer-detail',
    templateUrl: './customer-detail.component.html',
    styleUrls: ['./customer-detail.component.css']
})
export class CustomerDetailComponent implements OnInit {
    customer: Customer;
    customersList: Customer[];
    error: string;
    idPrevious: number;
    idNext: number;

    constructor(
        private http: HttpService,
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private customerService: CustomerService
    ) {
        this.customerService.getCustomersList().subscribe(
            (customers: Customer[]) => this.customersList = customers,
            (error: Response) => this.error = error.json()
        );

        const idCustomer: number = parseInt(activatedRoute.snapshot.params['idCustomer'], null);

        /* La 2ième instruction ne sert à rien sur le principe mais si F5 alors error sur find undefined */
        if (activatedRoute.snapshot.params['idCustomer']) {
            // Récupération de la liste de clients
            this.customerService.getCustomersList().subscribe(
                (customersList: Customer[]) => {
                    this.customersList = customersList;
                    this.prepareVariable();
                },
                (error: Response) => this.error = error.json()
            );
        } else {
            this.customer = new Customer();
        }
    }

    createOrUpdate(): void {
        this.http.put(this.http.wsCustomer.concat('createOrEdit'), this.customer).subscribe(
            () => {
                this.customerService.customersList = null;
                this.error = null; // Pour effacer le message d'erreur de l'appel précédent
                if (this.customer.id == null) {
                    this.customer = new Customer();
                } else {
                    this.router.navigate(['/customers-list']);
                }
            },
            (error: Response) => this.error = error.json()
        );
    }

    // Quand les paramètres d'un chemin changent, le composant n'est pas réinitialisé.
    // Donc il faut s'abonner au changement de param et refaire le traitement.
    ngOnInit() {
        this.activatedRoute.params.subscribe((params: Params) => {
            this.prepareVariable();
        });
    }

    private prepareVariable(): void {
        const indexCustomer: number = this.customersList.findIndex(
            customer => customer.id === parseInt(this.activatedRoute.snapshot.params['idCustomer'], null)
        );
        this.customer = this.customersList[indexCustomer];
        this.idPrevious = this.customersList[indexCustomer - 1] != null
            ? this.customersList[indexCustomer - 1].id
            : this.customersList[this.customersList.length - 1].id;
        this.idNext = this.customersList[indexCustomer + 1] != null
            ? this.customersList[indexCustomer + 1].id
            : this.customersList[0].id;
    }
}

The error is the following :

TypeError: Cannot read property 'findIndex' of undefined
    at CustomerDetailComponent.Array.concat.CustomerDetailComponent.prepareVariable (webpack:///src/app/customer/customer-detail/customer-detail.component.ts:73:57 <- src/test.ts:233183:47)
    at SafeSubscriber._next (webpack:///src/app/customer/customer-detail/customer-detail.component.ts:68:17 <- src/test.ts:233178:19)
    at SafeSubscriber.Array.concat.SafeSubscriber.__tryOrSetError (webpack:///~/rxjs/Subscriber.js:247:0 <- src/test.ts:18017:16)
    at SafeSubscriber.Array.concat.SafeSubscriber.next (webpack:///~/rxjs/Subscriber.js:187:0 <- src/test.ts:17957:27)
    at Subscriber.Array.concat.Subscriber._next (webpack:///~/rxjs/Subscriber.js:125:0 <- src/test.ts:17895:26)
    at Subscriber.Array.concat.Subscriber.next (webpack:///~/rxjs/Subscriber.js:89:0 <- src/test.ts:17859:18)
    at BehaviorSubject.Array.concat.BehaviorSubject._subscribe (webpack:///~/rxjs/BehaviorSubject.js:28:0 <- src/test.ts:114179:24)
    at BehaviorSubject.Array.concat.Observable._trySubscribe (webpack:///~/rxjs/Observable.js:171:0 <- src/test.ts:15883:25)
    at BehaviorSubject.Array.concat.Subject._trySubscribe (webpack:///~/rxjs/Subject.js:97:0 <- src/test.ts:29682:51)
    at BehaviorSubject.Array.concat.Observable.subscribe (webpack:///~/rxjs/Observable.js:159:0 <- src/test.ts:15871:65)

Even if that i know that i'm using my reals services , not stubs (what i would do ) but i don't know from what that error occurs exactly.

Suggestions ?

0 个答案:

没有答案