Angular 2 RC6 test HTTP.get抛出错误get()方法没有';不存在
我正在尝试为一个包含http.get方法的方法编写一个单元测试,但在让它工作时遇到了问题。我知道将用于Http的类设置为MockBackend是错误的,这也是我得到错误的原因:Angular 2 RC6 test HTTP.get抛出错误get()方法没有';不存在,http,angular,karma-jasmine,Http,Angular,Karma Jasmine,我正在尝试为一个包含http.get方法的方法编写一个单元测试,但在让它工作时遇到了问题。我知道将用于Http的类设置为MockBackend是错误的,这也是我得到错误的原因:get()方法不存在,但是我不知道应该为Http后面的mock类使用什么 describe('Http Service', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ S
get()方法不存在
,但是我不知道应该为Http后面的mock类使用什么
describe('Http Service', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
SharedHttpService,
{
provide: SharedCookieService,
useClass: MockSharedCookieService
}, {
provide: Http,
useClass: MockBackend
}
]
});
});
beforeEach(inject([ SharedHttpService, Http ], ( _httpService: SharedHttpService, _mockBackend: MockBackend ) => {
httpService = _httpService;
mockBackend = _mockBackend;
}));
describe('get', () => {
it(`should call setAuthToken and make the get request with the authorization headers`, () => {
let fakeUrl: string = 'www.fakeurl.com';
httpService.headers = mockHeaders;
spyOn(httpService, 'setAuthToken');
spyOn(httpService.http, 'get').and.callThrough();
mockBackend.connections.subscribe((connection: MockConnection) => {
let options: ResponseOptions = new ResponseOptions({
body: { }
});
connection.mockRespond(new Response(options));
});
httpService.get(fakeUrl, () => { })
.subscribe(() => {
expect(httpService.setAuthToken).toHaveBeenCalled();
expect(httpService.http.get).toHaveBeenCalledWith(fakeUrl, { headers: mockHeaders });
});
});
});
代码隐藏:
export class SharedHttpService {
private headers: Headers = new Headers();
constructor( private cookieService: SharedCookieService,
private http: Http ) { }
public get(address: string, callback: any): Observable<any> {
return this.setAuthToken()
.map(() => { })
.switchMap(() => {
return this.http.get(address, { headers: this.headers })
.map(callback)
.catch(( error: any ) => this.handleError(error));
});
}
}
导出类SharedHttpService{
私有头:头=新头();
构造函数(私有cookieService:SharedCookieService,
专用http:http{}
公共get(地址:string,回调:any):可观察{
返回此.setAuthToken()
.map(()=>{})
.switchMap(()=>{
返回this.http.get(地址,{headers:this.headers})
.map(回调)
.catch((错误:any)=>this.handleError(错误));
});
}
}
您需要使用MockBackend
而不是Http
,而是创建Http
。你可以在工厂里这样做
imports: [ HttpModule // this is needed ],
providers: [
SharedHttpService,
MockBackend,
BaseRequestOptions // @angular/http
{
provide: Http,
deps: [ MockBackend, BaseRequestOptions ],
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
return new Http(backend, options);
}
}
]
现在,您可以将MockBackend
注入测试中,以便模拟连接上的响应
// MockBackend not Http
beforeEach(inject([ SharedHttpService, MockBackend ],
( _httpService: SharedHttpService, _mockBackend: MockBackend ) => {
httpService = _httpService;
mockBackend = _mockBackend;
}));
另外,您需要使用异步测试,因为对subscribe
的调用是异步解析的
import { async } from '@angular/core/testing';
it('...', async(() => {
}));
另见