【发布时间】:2017-10-16 12:08:57
【问题描述】:
我在 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()'之后的所有内容都在之前执行......我做错了什么?
【问题讨论】:
标签: angular unit-testing jasmine karma-jasmine