我目前正在使用Angular2 RC6。我的服务设置如下:
import { Injectable } from '@angular/core';
import { TodoModel } from '../models/';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class TodoService {
baseURL = 'http://localhost:3000/todos';
constructor(private _http: Http) { }
getTodos() {
return this._http.get(this.baseURL).map((res: Response) => res.json());
}
}
我的测试设置如下:
import { MockBackend } from '@angular/http/testing';
import { Http, ConnectionBackend, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { TodoService } from './todo.service';
import { tick, async, inject, TestBed, fakeAsync } from '@angular/core/testing';
import { HttpModule, JsonpModule } from '@angular/http';
describe('TodoService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
{
provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}, deps: [MockBackend, BaseRequestOptions]
},
{provide: TodoService, useClass: TodoService},
{provide: MockBackend, useClass: MockBackend},
{provide: BaseRequestOptions, useClass: BaseRequestOptions}
]
});
});
it('should have a method to get all Todos',
fakeAsync(inject([TodoService, MockBackend], (todoService: TodoService, mockBackend: MockBackend) => {
let res: Response;
mockBackend.connections.subscribe(c => {
expect(c.request.url).toBe('http://localhost:3000/todos');
let response = new ResponseOptions({body: `[{"id": 5, "item": "do the laundry", "completed": false}]`});
c.mockRespond(new Response(response));
});
todoService.getTodos().subscribe((response) => {
res = response;
});
tick();
expect(res[0].id).toBe(5);
expect(res[0].item).toBe('do the laundry');
expect(res[0].completed).toBe(false);
}))
);
});
现在当我运行上面的单元测试时,我得到:
undefined is not a constructor (evaluating 'this._http.get(this.baseURL).map(function(res){__cov_70hjYvYxeq9mxqcOWgRVeQ.f['4']++;__cov_70hjYvYxeq9mxqcOWgRVeQ.s['9']++;return res.json();})') (line 9)
我不确定我究竟缺少什么,或者测试是否需要设置不同?
答案 0 :(得分:0)
在TodoService中导入丢失的rxjs地图
import 'rxjs/add/operator/map';