2017-08-17 99 views
1

我正在編寫一個基於Angular 4和Material 2的應用程序。它的工作原理是「現場」,但是當我決定編寫一些單元測試時,我遇到了麻煩。TypeError xxx.subscribe不是函數

看來,我有導致以下錯誤信息系統錯誤:

TypeError: this.serviceXXX.getAll(...).subscribe is not a function

這是我的服務代碼

import { Injectable } from '@angular/core'; 
import { Http, Headers, RequestOptions, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map' 

@Injectable() 
export class CompanyService { 

    constructor(private http: Http) { } 


    getAll() { 
     return this.http.get('/api/companies', this.jwt()).map((response: Response) => response.json()); 
    } 


    private jwt() { 
     // create authorization header with jwt token 
     const currentUser = JSON.parse(localStorage.getItem('currentUser')); 
     if (currentUser && currentUser.token) { 
      const headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token }); 
      return new RequestOptions({ headers: headers }); 
     } 
    } 

} 

我的組件:

import { Component, OnInit } from '@angular/core'; 
import {MdDialog, MdDialogRef} from '@angular/material'; 
import {Company} from '../../../models/_models'; 
import {CompanyService} from '../../../services/_services' 
import {Db} from './data-source' 
import {Observable} from 'rxjs/Observable'; 
import {Subscription} from 'rxjs/Subscription'; 

import {CompanyDetailsComponent} from '../company-details/company-details.component'; 

@Component({ 
    selector: 'app-company', 
    templateUrl: './company-listing.component.html', 
    styleUrls: ['./company-listing.component.scss'] 
}) 
export class CompanyListingComponent implements OnInit { 

    errorMessage: string; 
    dataSource; 
    displayedColumns: string[] = [ 'name', 'btns' ]; 

    constructor(public service: CompanyService, public dialog: MdDialog) { } 

    ngOnInit() { 
    this.loadAll(); 
    } 

    onCreate() { 
    this.showDetail(new Company('name')); 
    } 

    onEditUser(user: Company) { 
    } 

    onRemove(item: Company) { 

    } 

    loadAll() { 
    this.service.getAll() 
      .subscribe(
       data => { 
        this.dataSource = new Db(data); 
       }, 
       err => { 
        this.errorMessage = err; 
       }); 
    } 

    showDetail(item: Company) { 
    this.dialog.open(CompanyDetailsComponent, { 
     disableClose: true, 
      data: { 
      item: Company 
     } 
    } 
    ).afterClosed().subscribe(
     result => {this.loadAll(); } 
    ) 
    } 


} 

和我的測試班:

import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 
import { CompanyListingComponent } from './company-listing.component'; 
import { RouterTestingModule } from '@angular/router/testing'; 
import { MaterialModule, MdTableModule } from '@angular/material' 
import { CdkTableModule} from '@angular/cdk'; 
import { CompanyService } from './../../../services/_services'; 
import {mock, } from 'ts-mockito'; 
import 'rxjs/Rx'; 

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

    beforeEach(async(() => { 
    const companyServiceMock: CompanyService = mock(CompanyService) 
    TestBed.configureTestingModule({ 
     imports: [MaterialModule, 
       RouterTestingModule, 
       MdTableModule, 
       CdkTableModule], 
     declarations: [ CompanyListingComponent ], 
     providers: [ {provide: CompanyService, useValue: companyServiceMock} ] 
    }) 
    .compileComponents(); 
    })); 

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

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

我發現並閱讀了許多類似問題的問題,但沒有解決方案適用於我。

任何人都可以看到我做錯了什麼。

+0

只在測試過程中給出錯誤或者正常運行時工作正常嗎? –

+1

我不熟悉你正在使用的Mocking框架,但是在使用服務模擬器之前,你不需要爲getAll()方法設置一個存根? –

+0

Dean對你+1:你正在使用一個模擬服務,但是當它的getAll()方法被調用時,你不會告訴它要返回什麼。所以它最可能返回null或undefined或一個空對象。 –

回答

0

如文檔中ts-mockito says,嘗試捻熄GETALL方法在測試類:

beforeEach(async(() => { 
    const companyServiceMock: CompanyService = mock(CompanyService); 
    when(companyServiceMock.getAll()).thenReturn(Observable.of([])); 
    TestBed.configureTestingModule({ 
    imports: [MaterialModule, 
       RouterTestingModule, 
       MdTableModule, 
       CdkTableModule], 
    declarations: [ CompanyListingComponent ], 
    providers: [ {provide: CompanyService, useValue: companyServiceMock} ] 
    }) 
    .compileComponents(); 
})); 

我想是因爲你的companyServiceMock沒有使用磕碰定義getAll()方法出現錯誤。

+0

我認爲你是正確的。我已經添加了這一行:when(companyServiceMock.getAll).thenReturn((=)=> Observable.of([])),現在我有這個錯誤消息:失敗:無法讀取undefined –

+0

@lg的屬性'add'。 lindstrom這個'add'屬性用在哪裏?我似乎無法在您的代碼中找到它 – samAlvin

+0

我不知道它在哪裏使用,,,也許在ts-mockito ,,但我無法找到它.. –

相關問題