类型错误:无法读取 Jasmine 中未定义的属性(读取“订阅”)

2024-04-20

我正在尝试为以下方法编写测试用例:-

 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();
 });

从这段代码中,我的测试用例已被覆盖,但我收到以下错误:-


你打电话吗subscriptionPackages in the ngOnInit or the constructor的组件?

如果你在ngOnInit,你需要嘲笑returnValue在第一个之前fixture.detectChanges()。首先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();
 });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类型错误:无法读取 Jasmine 中未定义的属性(读取“订阅”) 的相关文章

随机推荐