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