我有一个函数可以调用另一个本身使用http订阅的函数,而我在测试它时遇到了麻烦...
MyComponent
id = 1;
myFunct() {
this.myService.delete(this.id);
}
我的服务
delete(id) {
this.http.delete(this.myUrl + '/' + id).subscribe()
}
测试
let mockService;
beforeEach(() => {
TestBed.configureTestingModule({
mockService = createSpyObj(['delete']);
imports: ...,
declarations: ...,
providers: [
{provide: MyService, useValue: mockService}
]
}).compileComponents();
fixture = ...;
component = ...;
fixture.detectChanges();
});
it('should test delete', () => {
mockService.delete.and.returnValue({ subscribe: () => {} });
component.myFunct();
expect(mockService.delete).toHaveBeenCalledTimes(1);
});
我的测试返回错误:
无法读取未定义的属性“ subscribe”
答案 0 :(得分:1)
常见的模式是从您的服务方法返回observable并在其中订阅。零件。
类似的东西:
MyComponent
id = 1;
myFunct() {
this.myService.delete(this.id).subscribe(
(result) => console.log(result),
(error) => console.log(error)
};
我的服务
delete(id): Observable<any> {
this.http.delete(this.myUrl + '/' + id)
}
测试
imports {of} from 'rxjs'
let mockService;
beforeEach(() => {
TestBed.configureTestingModule({
mockService = createSpyObj(['delete']);
imports: ...,
declarations: ...,
providers: [
{provide: MyService, useValue: mockService}
]
}).compileComponents();
fixture = ...;
component = ...;
fixture.detectChanges();
});
it('should test delete', () => {
mockService.delete.and.returnValue(of({id: 1}));
component.myFunct();
expect(mockService.delete).toHaveBeenCalledTimes(1);
});