gpt4 book ai didi

http - Angular 2 RC6 测试 HTTP.get 抛出错误 get() 方法不存在

转载 作者:可可西里 更新时间:2023-11-01 17:06:24 26 4
gpt4 key购买 nike

我正在尝试为包含 http.get 方法的方法编写单元测试,但在使其正常工作时遇到了问题。我知道将用于 Http 的类设置为 MockBackend 是错误的,这就是我收到错误的原因:get() 方法不存在 但是我不知道我应该为模拟类使用什么在 http 后面。

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));
});
}
}

最佳答案

您需要使用 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 注入(inject)到测试中,以便您可以模拟连接上的响应。

                                  // MockBackend not Http
beforeEach(inject([ SharedHttpService, MockBackend ],
( _httpService: SharedHttpService, _mockBackend: MockBackend ) => {
httpService = _httpService;
mockBackend = _mockBackend;
}));

另一件事,您需要使用异步测试,因为对 subscribe 的调用是异步解析的

import { async } from '@angular/core/testing';

it('...', async(() => {

}));

另见 Angular 2 Testing - Async function call - when to use

关于http - Angular 2 RC6 测试 HTTP.get 抛出错误 get() 方法不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com