2016-12-01 131 views
1

我想寫我的服務寫在角2.1.0一些測試:Angular2測試:服務返回函數,而不是對象數組

@Injectable() 
export class MyService { 
    api_base_url = 'http://' + environment.apiHost + ':5000/api/'; 

    constructor(private http: Http) { 
    } 

    getMyObjs(query): Observable<MyObj[]> { 
     let params = new URLSearchParams(); 

     if (query != null && query.length > 0) 
      params.set('q', query); 

     return this.http.get(this.api_base_url + 'entries/' + pipelineId, {search: params}) 
      .map(this.extractData) 
      .catch(this.handleError); 
    } 

    private extractData(res: Response) { 
     let body = res.json(); 
     return body.entries || {}; 
    } 

    private handleError(error: any) { 
     // In a real world app, we might use a remote logging infrastructure 
     // We'd also dig deeper into the error to get a better message 
     let errMsg = (error.message) ? error.message : 
      error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
     console.error(errMsg); // log to console instead 
     return Observable.throw(errMsg); 
    } 

} 

這裏是測試至今:

describe('Service: Entry',() => { 

beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     providers: [ 
      BaseRequestOptions, 
      MockBackend, 
      MyService, 
      { 
       provide: Http, 
       useFactory: (backend: MockBackend, options: BaseRequestOptions) => { 
        return new Http(backend, options); 
       }, 
       deps: [MockBackend, BaseRequestOptions] 
      } 
     ] 
    }); 

})); 

it('should return myobjs', inject([MockBackend, MyService], (backend: MockBackend, service: MyService) => { 
    const my_body = JSON.stringify([ 
     { 
      "timestamp": "2016.01.01T12:55:00Z", 
      "level": 0, 
     } 
    ]); 
    const baseResponse = new Response(new ResponseOptions({body: my_body, status: 200})) 
    backend.connections.subscribe((connection: MockConnection) => { 
     return connection.mockRespond(baseResponse); 
    }); 

    service.getMyObjs(null).subscribe((obs: MyObj[]) => { 
     console.log(obs); 
     expect(obs.length).toBe(1); 
    }); 

})); 
}); 

此測試失敗,說Expected 0 to be 1.。 console.log顯示LOG: function obs() { ... }。我不明白爲什麼這是一個函數而不是一組對象。 我正在用ng test命令運行測試。

回答

1

在模擬的HTTP響應中,您返回的對象結構與extractData()期望的不同。我想它應該看起來像這樣:

// ... stuff ... 
it('should return myobjs', ...) => { 
    const my_body = JSON.stringify({ 
     entries: [{ 
      "timestamp": "2016.01.01T12:55:00Z", 
      "level": 0, 
     }] 
    }); 
+0

你只是保存我的一天。 – fivunlm

相關問題