我正在努力对构造函数中具有异步Http调用的Angular2服务进行单元测试(现在我想知道它应该首先在这里)。
下面的示例代码 - 模拟的调用似乎永远不会被执行,我不知道我应该把它放在哪里。测试失败,因为我声明的属性在执行时是未定义的。我尝试使用fakeAsync和tick()但是它们都没有用。
服务类:
@Injectable
export class Service {
private data: any; //some object that will be returned from server
constructor(private http: Http) {
this.http.get('url')
.map( (res: Response) => res.json())
.subscribe(res => this.data = res);
}
getId() {
return data.id;
}
}
单元测试:
describe('service test...', () => {
let service: Service;
let backend: MockBackend;
let result = { id: 123 };
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
Service,
{
provide: Http,
useFactory: (mockBackend, options) => {
return new Http(mockBackend, options);
},
deps: [MockBackend, BaseRequestOptions]
},
MockBackend,
BaseRequestOptions
]
});
});
beforeEach(inject([Service, MockBackend], (s, mb) => {
service = s;
backend = mb;
backend.connections.subscribe((conn) => {
conn.mockRespond(new Response(new ResponseOptions({body: result})));
});
}));
describe('test...', () => {
it('should have id of 123...', async(() => {
expect(service.getId()).toEqual(123);
}));
});
});