2
我想爲我的服務編寫Http請求的單元測試。使用MockBackend來測試函數,然後調用.map
我有一項服務返回一個Http.get()
請求後跟一個.map()
。我無法讓我的模擬後端返回.map()
上沒有錯誤的內容。我得到的錯誤是:
this._http.get(...).map is not a function
我一直在使用this article作爲我的主要指導貫穿始終。
如果我從我的服務功能中刪除.map()
,我不會收到任何錯誤。我怎樣才能讓我的嘲弄反應有一個我可以調用的.map()
函數?
注:我目前使用的RC.4
這裏是我的服務:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AppSettings } from '../../../settings';
import { Brand } from '../../models/index';
@Injectable()
export class BrandDataService {
allBrands : Brand[];
groups : any;
groupNames : string[];
constructor (
private _http : Http
) {}
/**
* Get all brands
*/
public getAllBrands() :Observable<any> {
let url = AppSettings.BRAND_API_URL + 'brands';
return this._http.get(url)
.map(this.createAndCacheBrands)
.catch((error) => {
return Observable.throw(error);
});
}
private createAndCacheBrands (res:Response) {
...
}
}
這裏是我的規格文件,該文件是使用MockBackend
和其他相關庫嘲笑後端這些測試:
// vendor dependencies
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { addProviders, inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
// Service to test
import { BrandDataService } from './brandData.service';
describe('Brand data service',() => {
let service : BrandDataService = null;
let backend : MockBackend = null;
// Provide a mock backend implementation
beforeEach(() => {
addProviders([
MockBackend,
BaseRequestOptions,
{
provide : Http,
useFactory : (backendInstance : MockBackend, defaultOptions : BaseRequestOptions) => {
return new Http(backendInstance, defaultOptions);
},
deps : [MockBackend, BaseRequestOptions]
},
BrandDataService
])
})
beforeEach (inject([BrandDataService, MockBackend], (_service : BrandDataService, mockBackend : MockBackend) => {
service = _service;
backend = mockBackend;
}));
it ('should return all brands as an Observable<Response> when asked', (done) => {
// Set the mock backend to respond with the following options:
backend.connections.subscribe((connection : MockConnection) => {
// Make some expectations on the request
expect(connection.request.method).toEqual(RequestMethod.Get);
// Decide what to return
let options = new ResponseOptions({
body : JSON.stringify({
success : true
})
});
connection.mockRespond(new Response(options));
});
// Run the test.
service
.getAllBrands()
.subscribe(
(data) => {
expect(data).toBeDefined();
done();
}
)
});
});
哦,我很生氣 - 我今天早些時候有這個問題並在其他地方修復它。我不知道爲什麼它在我這裏沒有發生。謝謝你指出明顯! – dafyddPrys
@dafyddPrys不要擔心,它發生在每個人身上。我犯了這個確切的錯誤兩三次,這就是我記憶的方式。 :-) –
你知道我需要導入以獲得'.map()。catch()'嗎? - 編輯:原來是'rxjs/add/operator/catch'。 – dafyddPrys