我在Angular 4中编写了一个应用程序,并且我已经使用http get请求获得了ngOnInit函数。我想编写单元测试,但不知道如何模拟请求。
ngOnInit() {
this.http.get<any>('someurl', {
headers: new HttpHeaders().set('Authorization', 'authorization'`)
})
.subscribe(
(res) => {
this.servB = res.items
.map((item) => {
return new ServB(item)
});
}
);
}
到目前为止我的单元测试看起来像这样:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpClientModule, HttpModule ],
declarations: [ ServBComponent ],
providers : [
{ provide: 'someurl', useValue: '/' },
{ provide: XHRBackend, useClass: MockBackend }
]
})
.compileComponents().then(() => {
fixture = TestBed.createComponent(ServiceBrokersComponent);
component = fixture.componentInstance;
});
it('should get the servb list', async(inject([XHRBackend], (mockBackend) => {
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: data
})));
});
fixture.detectChanges();
fixture.whenStable().then(()=> {
console.log('anything');
});
})));
但它不起作用。它仍然从服务器请求数据,不返回模拟值。加上'whenStable()'之后的所有内容都在之前执行......我做错了什么?
答案 0 :(得分:0)
您需要导入HttpClientTestingModule
而不是HttpClientModule
,如下所示:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
HttpService
]
});
});