TypeError:无法读取Jasmine中未定义(正在读取订阅)的属性 [英] TypeError: Cannot read properties of undefined (reading 'subscribe') in Jasmine
本文介绍了TypeError:无法读取Jasmine中未定义(正在读取订阅)的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为以下方法编写测试用例:-
subscriptionPackages() {
this.managePackageService.getPackages().subscribe(
(response) => {
this.packagePlan = response;
},
(httpErrorRes) => {
}
);
}
我已经在我的spec.ts文件中尝试了以下代码片段来覆盖上面的代码:-
fdescribe('AddProductComponent', () => {
let component: AddProductComponent;
let fixture: ComponentFixture<AddProductComponent>;
let packageServiceStub = jasmine.createSpyObj('ManagePackageService', ['getPackages']);
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule,ReactiveFormsModule,FormsModule,ToastrModule.forRoot(),
TranslateModule.forRoot(), NgSelectModule],
declarations: [ AddProductComponent ],
providers :[AppConfig,
{ provide: ManagePackageService, useValue: packageServiceStub }]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AddProductComponent);
component = fixture.componentInstance;
component.packagePlan = [{'name':'basic', 'id':1}, {'name':'advance', 'id':2}, {'name':'premium', 'id':3}];
fixture.detectChanges();
});
it('should create subscriptionPackages', () => {
const mockpackageResponse = [];
packageServiceStub.getPackages.and.returnValue(of(mockpackageResponse));
component.subscriptionPackages();
expect(component.packagePlan).toBeTruthy();
});
从这段代码中,我覆盖了我的测试用例,但我得到以下错误:-
推荐答案
是否在组件的ngOnInit
或constructor
中调用subscriptionPackages
?
如果在ngOnInit
中调用,则需要在第一个fixture.detectChanges()
之前模拟returnValue
。第一个fixture.detectChanges()
是在调用ngOnInit
时。
beforeEach(() => {
fixture = TestBed.createComponent(AddProductComponent);
component = fixture.componentInstance;
// !! Move this line here if calling subscriptionPackages in ngOnInit !!
packageServiceStub.getPackages.and.returnValue(of(mockpackageResponse));
component.packagePlan = [{'name':'basic', 'id':1}, {'name':'advance', 'id':2}, {'name':'premium', 'id':3}];
fixture.detectChanges();
});
it('should create subscriptionPackages', () => {
const mockpackageResponse = [];
component.subscriptionPackages();
expect(component.packagePlan).toBeTruthy();
});
beforeEach(() => {
// !! Move this line here if calling subscriptionPackages in constructor !!
packageServiceStub.getPackages.and.returnValue(of(mockpackageResponse));
fixture = TestBed.createComponent(AddProductComponent);
component = fixture.componentInstance;
component.packagePlan = [{'name':'basic', 'id':1}, {'name':'advance', 'id':2}, {'name':'premium', 'id':3}];
fixture.detectChanges();
});
it('should create subscriptionPackages', () => {
const mockpackageResponse = [];
component.subscriptionPackages();
expect(component.packagePlan).toBeTruthy();
});
这篇关于TypeError:无法读取Jasmine中未定义(正在读取订阅)的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文