Javascript 角度单元测试:如何在ngOnInIt()中进行单元测试订阅?
待测试部件:Javascript 角度单元测试:如何在ngOnInIt()中进行单元测试订阅?,javascript,angular,unit-testing,jasmine,karma-jasmine,Javascript,Angular,Unit Testing,Jasmine,Karma Jasmine,待测试部件: export class ComponentDetailsComponent implements OnInit { ngOnInit() { this.componentDetailsService.currentProperties.subscribe((data) => { this.loader.hideLoader(); this.showPopup = d
export class ComponentDetailsComponent implements OnInit {
ngOnInit() {
this.componentDetailsService.currentProperties.subscribe((data) => {
this.loader.hideLoader();
this.showPopup = data.showPopup;
.....more code....
}
规格:
class ComponentDetailsServiceStub {
defaultProperties ={
showToolbar: false,
showPopup: true, //show popup is set to true here
refresh: false,
};
propertiesSource = new BehaviorSubject(this.defaultProperties);
currentProperties = this.propertiesSource.asObservable();
setDefaultCancelClicked(){}
}
it('should set showPopup to correct value', () => {
componentDetailsService.propertiesSource.next({
showToolbar: true,
showPopup: false, // show popup is set to false
refresh: false,
});
expect(subject.showPopup).toBe(true) ///this always passes
});
你不必写那么多的步骤就可以通过了
import { of } from 'rxjs';
....
class ComponentDetailsServiceStub {
defaultProperties ={
showToolbar: false,
showPopup: true, //show popup is set to true here
refresh: false,
};
currentProperties = of(defaultProperties); // will convert to Observable
setDefaultCancelClicked(){}
}
您的测试用例可以是:
it('should set showPopup to correct value', () => {
subject.ngOnInit(); // jasmine will internally call subscribe on stub service created and return the stub value assigned.
expect(subject.showPopup).toBe(true);
});
请给出一个答案;这是怎么联系起来的?我不会测试showPopup
属性,我会测试弹出窗口是否显示。此外,您可能需要一个检测更改。