使用 createSpyObj 对可观察对象进行单元测试
unit testing observables with createSpyObj
我有一个调用另一个本身使用 http 订阅的函数,但我无法对其进行测试...
我的组件
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);
});
我的测试返回错误:
Cannot read property 'subscribe' of undefined
常见的模式是 return 从您的服务方法中观察到并在内部订阅,例如。零件。
像这样:
我的组件
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);
});
我有一个调用另一个本身使用 http 订阅的函数,但我无法对其进行测试...
我的组件
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);
});
我的测试返回错误:
Cannot read property 'subscribe' of undefined
常见的模式是 return 从您的服务方法中观察到并在内部订阅,例如。零件。
像这样:
我的组件
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);
});