在Angular 4中模拟http请求 [英] mock http request in Angular 4
本文介绍了在Angular 4中模拟http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Angular 4中编写了一个应用程序,并且我已经使用http get请求获得了ngOnInit函数。我想编写单元测试,但不知道如何模拟请求。
I write an app in Angular 4 and I've got ngOnInit function with http get request. I want to write unit test, but don't know how to mock the request.
ngOnInit() {
this.http.get<any>('someurl', {
headers: new HttpHeaders().set('Authorization', 'authorization'`)
})
.subscribe(
(res) => {
this.servB = res.items
.map((item) => {
return new ServB(item)
});
}
);
}
到目前为止我的单位测试看起来像这样:
and my unit test so far looks like this:
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()'之后的所有内容都在之前执行...我做错了什么?
but it doesn't work. It still requests data from the server, doesn't return the mocked value. Plus everything that is after 'whenStable()' is executed before... What am I doing wrong?
推荐答案
你需要导入 HttpClientTestingModule
而不是 HttpClientModule
,如下所示:
You need to import HttpClientTestingModule
instead of HttpClientModule
, like this:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
HttpService
]
});
});
这篇关于在Angular 4中模拟http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文