我有一个组件可以订阅ngOnInit中从服务返回的observable。我也有方法(updateData),该方法从服务订阅可观察的内容,但也更新订阅中的某些属性。我需要创建一个测试来检查在调用updateData时此属性是否更改为正确的值。
组件片段:
ngOnInit() {
this.myService.loadData().subscribe() => {
// some code here
});
}
...
public updateData() {
this.myService.updateData(this.data).subscribe(() => {
this.dataUpdated = true;
});
}
测试设置
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let myServiceSpy: jasmine.SpyObj<MyService>;
const dataMock = {};
const updateResponseMock = {};
beforeEach(async(() => {
myServiceSpy = jasmine.createSpyObj('DesignPickerService', [
'loadData',
'updateData'
]);
myServiceSpy.loadData.and.returnValue(
cold('-a|', { a: dataMock })
);
myServiceSpy.updateData.and.returnValue(
cold('--b|', { b: updateResponseMock })
);
TestBed.configureTestingModule({
declarations: [
MyComponent,
],
providers: [
{
provide: MyService,
useFactory: () => {
return myServiceSpy;
}
}
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
describe('Tests', () => {
it('updateData should set dataUpdated to true', () => {
??? // some code to wait for myService.loadData to finish
component.dataUpdated = false;
component.updateData();
??? // some code to wait for myService.updateData to finish
expect(component.dataUpdated).toBe(true);
})
});
});
我想添加那些缺少的行,以便测试通过。任何帮助将不胜感激。
答案 0 :(得分:0)
对不起,我不敢相信您正在谈论http呼叫,您可以尝试这种方式,但是我没有使用service,您可以轻松地对其进行嘲笑。
fit('应该返回正确的数据',(完成)=> {
expect(component.dataUpdated).toEqual(false);
component.getData().subscribe(data => {
expect(data).toEqual([1, 2, 3, 4]);
expect(component.dataUpdated).toEqual(true);
done();
}
);
});
export class ObservableTddComponent implements OnInit {
dataUpdated;
constructor() {
this.dataUpdated = false;
}
ngOnInit() {
this.getData().subscribe( (x) => {
this.dataUpdated = true;
});
}
getData(){
return of([1,2,3,4]).pipe(delay(500));
}
}
有关更多信息,请阅读以下文章:https://itnext.io/a-quick-tip-on-testing-observables-e2fbdebef4c