我正在尝试使用MockBackend为异步http服务编写角度2单元测试,但是获取http.get未定义错误。这是我的代码:
Http服务:
import { Injectable } from '@angular/core';
import { Http,Headers,RequestOptions,Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
@Injectable()
export class HttpService {
constructor(private _http: Http) {}
/**
* Http request will time out if not received response within 20 sec
*
* @param url
* @returns {Observable<R>}
*/
getData(url : string) {
return this._http.get(url)
.timeout(20000, new Error('delay exceeded'))
.map(response => response.json());
}
}
我正在编写单元测试的自定义组件方法:
private loadDetails(input : string){
this._httpService.getData("/api/test"+ input)
.subscribe(
data => {this.user = data,
// Some more logic in here based on data
},
error => { console.log( error);}
);
}
单元测试:
import { HttpService } from "../shared/services/http.service";
import {
async,
inject,
fakeAsync,
TestBed
} from '@angular/core/testing';
import {
Http,
BaseRequestOptions,
Response,
BaseResponseOptions,
ResponseOptions
} from '@angular/http';
import { HttpModule } from '@angular/http';
import {
MockBackend,
MockConnection
} from '@angular/http/testing';
import { Observable } from 'rxjs/Rx';
import { TestingComponent } from './testing.component';
const mockHttpProvider = {
deps: [ MockBackend, BaseRequestOptions ],
useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}
}
describe('testingComponent', () => {
let fixture,testingComponent;
// provide our implementations or mocks to the dependency injector
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
CustomComponent
],
providers: [
HttpService,
MockBackend,
BaseRequestOptions,
{provide: Http, useValue: mockHttpProvider}
]
});
fixture = TestBed.createComponent(PortfolioComponent);
testingComponent = fixture.debugElement.componentInstance;
});
it('should call loadDetails to load user details', inject(
[IPIQHttpService, MockBackend],
fakeAsync((service: HttpService, backend: MockBackend) => {
backend.connections.subscribe((connection: MockConnection) => {
let mockResponseBody= {
id: '123',
title: 'test',
empno: '456'
};
let response = new ResponseOptions({body: JSON.stringify(mockResponseBody)});
connection.mockRespond(new Response(response));
});
testingComponent.loadUserDetails('123');
expect(testingComponent.user.empno).toEqual('456');
})));
});
当我调用testingComponent.loadUserDetails(&#39; 123&#39;)来调用http服务时,我得到http.get方法未定义。
知道我在这里做错了吗?
答案 0 :(得分:4)
const mockHttpProvider = {
provide: Http,
deps: [ MockBackend, BaseRequestOptions ],
useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}
}
TestBed.configureTestingModule({
imports: [HttpModule], // <<<=== added
declarations: [
CustomComponent
],
providers: [
HttpService,
MockBackend,
BaseRequestOptions,
mockHttpProvider
]
});
答案 1 :(得分:1)
最后它正在发挥作用。以下是我所做的更改:
const mockHttpProvider =
{
provide: Http,
deps: [ MockBackend, BaseRequestOptions ],
useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) =>
{ return new Http(backend, defaultOptions); }
}
TestBed.configureTestingModule({
imports: [HttpModule], // <<<=== added
declarations: [
CustomComponent
],
providers: [
HttpService,
MockBackend,
BaseRequestOptions,
mockHttpProvider
]
});
it('should call loadDetails to load user details', inject([HttpService, MockBackend, Http], (_httpService, backend, http) => {
backend.connections.subscribe(connection => {
let mockResponseBody= {
id: '123',
title: 'test',
empno: '456'
};
let response = new ResponseOptions({body: JSON.stringify(mockResponseBody)});
connection.mockRespond(new Response(response));
});
testingComponent.loadDetails('123');
expect(testingComponent.user.empno).toEqual('456');
}));