我想为我在Angular 2.1.0中编写的服务编写一些测试:
@Injectable()
export class MyService {
api_base_url = 'http://' + environment.apiHost + ':5000/api/';
constructor(private http: Http) {
}
getMyObjs(query): Observable<MyObj[]> {
let params = new URLSearchParams();
if (query != null && query.length > 0)
params.set('q', query);
return this.http.get(this.api_base_url + 'entries/' + pipelineId, {search: params})
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.entries || {};
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
到目前为止,这是测试:
describe('Service: Entry', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
BaseRequestOptions,
MockBackend,
MyService,
{
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
return new Http(backend, options);
},
deps: [MockBackend, BaseRequestOptions]
}
]
});
}));
it('should return myobjs', inject([MockBackend, MyService], (backend: MockBackend, service: MyService) => {
const my_body = JSON.stringify([
{
"timestamp": "2016.01.01T12:55:00Z",
"level": 0,
}
]);
const baseResponse = new Response(new ResponseOptions({body: my_body, status: 200}))
backend.connections.subscribe((connection: MockConnection) => {
return connection.mockRespond(baseResponse);
});
service.getMyObjs(null).subscribe((obs: MyObj[]) => {
console.log(obs);
expect(obs.length).toBe(1);
});
}));
});
此测试未能说Expected 0 to be 1.
。 console.log显示LOG: function obs() { ... }
。我不明白为什么这是一个函数而不是一个对象数组。
我用ng test
命令运行测试。
答案 0 :(得分:1)
在模拟的HTTP响应中,您返回的对象结构与extractData()
期望的结构不同。我想它应该是这样的:
// ... stuff ...
it('should return myobjs', ...) => {
const my_body = JSON.stringify({
entries: [{
"timestamp": "2016.01.01T12:55:00Z",
"level": 0,
}]
});