Angular - 测试 - 无法初始化子组件

问题描述 投票:0回答:1

我正在尝试测试扩展基本组件的子组件。 SubComponent 重写父组件中的 ngOnInit() ,而 Base comp 在 ngOnit 和 ngOnDestroy 方法中包含一些逻辑。 我收到的错误如下

组件在清理过程中抛出错误

任何人都可以解决如何单独测试子组件并正确初始化它的问题吗?

子组件:

@Component({
  selector: '',
  templateUrl: '',
})
export class SubComponent
  extends BaseComponent<any>
  implements OnInit, AfterViewInit
{

  constructor(
    protected override service1: Service1<any>,
    protected override service2: Service2,
  ) {
    super(service1, service2, true);
  }

  override ngOnInit(): void {
    super.ngOnInit();
  }
}

基础组件:

@Component({
  selector: 'base',
  standalone: true,
  template: '',
})
export class BaseDialogComponent<T> implements OnInit, OnDestroy {
  

  constructor(
    protected service1: Service1<T>,
    protected service2: Service2,
    @Inject(DIALOG_CLOSING_CONFIG) dialogClosingConfig: boolean
  ) {
    this.enableDialogClosing = dialogClosingConfig;
  }

  @HostListener('window:popstate', ['$event'])
  onPopState(event: any) {
    .....
  }

  ngOnInit() {
    ....
  }

  ngOnDestroy() {
    this.service2.something();
  }
}

子组件.spec

describe('SubComponent', () => {
  let component: SubComponent;
  let fixture: ComponentFixture<SubComponent>;
  let someSubComponentService: SubComponentService;
  let subComponentServiceStub: Partial<any>;

  const createComponent = () => {
    fixture = TestBed.createComponent(SubComponent);
    fixture.detectChanges();
    return fixture;
  };

  beforeEach(async () => {
    subComponentServiceStub= {
      initialize: () => {},
    };

    await TestBed.configureTestingModule({
      imports: [TestModule],
      declarations: [SubComponent],
      providers: [
        {
          provide: SubComponentService,
          useValue: subComponentServiceStub,
        },
      ],
    }).compileComponents();

    component = createComponent().componentInstance;

    someSubComponentService= TestBed.inject(
      SubComponentService
    );
    spyOn(someSubComponentService, 'initialize');    
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });  
});
angular unit-testing jasmine angular-test
1个回答
0
投票

实际上,问题是由基础组件的 ngOnDestroy() 内部定义的一些依赖服务操作('service2.something()')引起的。向测试床模块提供此服务后,问题消失了,组件已正确初始化。

© www.soinside.com 2019 - 2024. All rights reserved.