我正在尝试为发出 Http 请求的服务编写单元测试。
我有一个服务,它返回一个Http.get()
请求,后跟一个.map()
. 我无法让我的模拟后端返回在.map()
. 我得到的错误是:
this._http.get(...).map is not a function
我一直使用这篇文章作为我的主要指南。
如果我.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();
}
)
});
});