在Angular 4中模拟http请求
问题描述:
我在Angular 4中编写了一个应用程序,并且通过http get请求获得了ngOnInit函数。我想编写单元测试,但不知道如何模拟请求。在Angular 4中模拟http请求
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()'之前执行的所有内容......我做错了什么?
答
您需要导入HttpClientTestingModule
而不是HttpClientModule
,像这样:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
HttpService
]
});
});
它并不能帮助不幸的是 –
这是否帮助:http://www.syntaxsuccess.com/viewarticle/mocking-http-request -with-HttpClient的功能于角 – DeborahK