TypeError: Cannot read properties of undefined (reading 'subscribe') in Jasmine

TypeError: Cannot read properties of undefined (reading 'subscribe') in 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();
 });