Angular 2 个单元测试 http.get 未定义
Angular 2 unit test http.get undefined
我正在尝试使用 MockBackend 为异步 http 服务编写 angular 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('123') 来调用 http 服务时,我得到 http.get 方法未定义。
知道我做错了什么吗?
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
]
});
终于成功了。以下是我所做的更改:
- 导入了 HttpModule 并改变了我使用 mockHttpProvider 的方式,正如@Günter Zöchbauer 在之前 post 中所建议的那样:
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
]
});
- 更改了我的单元测试并删除了 fakeAsync:
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');
}));
我正在尝试使用 MockBackend 为异步 http 服务编写 angular 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('123') 来调用 http 服务时,我得到 http.get 方法未定义。
知道我做错了什么吗?
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
]
});
终于成功了。以下是我所做的更改:
- 导入了 HttpModule 并改变了我使用 mockHttpProvider 的方式,正如@Günter Zöchbauer 在之前 post 中所建议的那样:
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
]
});
- 更改了我的单元测试并删除了 fakeAsync:
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');
}));