![](/img/trans.png)
[英]Angular Unit Test - How to inject dependencies to TestBed by using useValue in the TestBed provider
[英]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
- Approved
和Pending
。
因此,在初始化測試台時,我會將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。
我們可以在Angular的TestBed
本身中看到非常好的:
createComponent<T>(component: Type<T>): ComponentFixture<T> {
this._initIfNeeded();
..
}
private _initIfNeeded(): void {
if (this._instantiated) {
return;
}
..
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.