如何模拟 Observable return angular 服务?
How to mock the Observable return angular service?
this.variable = this.service.getMydata();
以上服务正在返回 Observable 并且我订阅的变量如下。
this.variable.subscribe(data => { My logic here});
如何在 angular 6 中对此进行正确的单元测试?
试试这个:
const mockResponse = {
// ...
};
spyOn(service, 'getMydata').and.returnValue(of(mockResponse));
将服务和方法模拟为 return observable
const mockService = {
getMydata: {
return of(<Response>)
}
}
TestBed.configureTestingModule({
declarations: [...],
providers: [{provide: Service, useValue: mockService}]
})
this.variable = this.service.getMydata();
以上服务正在返回 Observable 并且我订阅的变量如下。
this.variable.subscribe(data => { My logic here});
如何在 angular 6 中对此进行正确的单元测试?
试试这个:
const mockResponse = {
// ...
};
spyOn(service, 'getMydata').and.returnValue(of(mockResponse));
将服务和方法模拟为 return observable
const mockService = {
getMydata: {
return of(<Response>)
}
}
TestBed.configureTestingModule({
declarations: [...],
providers: [{provide: Service, useValue: mockService}]
})