繁体   English   中英

覆盖测试平台提供者以在单元测试中使用其他注入值

[英]Override testbed provider to use other inject value in unit test

我试图覆盖测试平台提供程序,因为我必须测试两种情况,即我向模式中注入的值不同。

到目前为止,我已经尝试过类似的方法,但是没有运气。

  theTestBed.overrideProvider('content', { useValue: 'Pending' });
  theTestBed.compileComponents();
  fixture = theTestBed.createComponent(RequestChangeStatusModalComponent);
  component = fixture.componentInstance;
  component.ngOnInit();
  fixture.changeDetectorRef.detectChanges();
  fixture.detectChanges();
  statusOptions = component.changeStatusData.statusOptions;
  expect(statusOptions[0]).toBe('Budgeted Line Item');
  expect(statusOptions[1]).toBe('Considered for Board');

这种情况是我有一个模态组件,我向其中注入了requestType参数。

    @Inject('content') private requestType: string

在ngOnInit()中,我根据requestType是设置下拉选项。

现在,我正在为组件编写单元测试。 有两个值requestType - ApprovedPending

因此,在初始化测试台时,我会将Approved值传递给模态。

theTestBed = TestBed.configureTestingModule({
  declarations,
  imports,
  [{
    provide: 'content',
    useValue: 'Approved'
  }]
});

但是问题是如何重置提供程序以将其他requestType作为Pending传递给模式?

谁能告诉我如何达到理想的结果?

也许我可以在不覆盖提供程序的情况下测试我要测试的内容?

如果它是在模块级别声明的提供程序,则可以尝试在configureTestingModule()调用期间“覆盖”它,并删除overrideProvider()调用:

  TestBed.configureTestingModule({
    imports:   [],
    declarations: [RequestChangeStatusModalComponent],
    providers: [
      { provide: 'content', useValue: 'Pending'}
    ]
  });
  TestBed.compileComponents();

如果它是在组件级别上声明的服务提供者,则必须使用overrideComponent才能检查其提供者:

  TestBed.configureTestingMod
  TestBed.overrideComponent(HeroDetailComponent, {
    set: {
      providers: [
        { provide: HeroDetailService, useClass: HeroDetailServiceSpy }
      ]
    }
  })

更新createComponent()beforeEach移到每个it测试用例中,确实解决了我的测试场景中的问题。

  beforeEach(() => {
    // the createComponent() in the beforeEach causes the problem 
    //
    // fixture = TestBed.createComponent(FlightSearchComponent);
    // component = fixture.componentInstance;
    // fixture.detectChanges();
  });

  it('should use content Pending', () => {
    fixture = TestBed.createComponent(FlightSearchComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    expect(component.value).toBe('Pending');
  });

  it('should use content Approved', () => {
    TestBed.overrideProvider('content', { useValue: 'Content 2'});
    fixture = TestBed.createComponent(FlightSearchComponent);
    fixture.detectChanges();
    expect(component.value).toBe('Approved');
  });

问题在于,通过两次调用createComponent ,第二次调用使用的是已实例化的ComponentFactories和ModuleFactories。

我们可以在AngularTestBed本身中看到非常好的:

  createComponent<T>(component: Type<T>): ComponentFixture<T> {
    this._initIfNeeded();
    ..
  }

  private _initIfNeeded(): void {
    if (this._instantiated) {
      return;
    }
    ..
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM