![](/img/trans.png)
[英]Angular / Redux Cannot read property 'dispatch' of undefined
[英]Angular + Redux Jasmine testing "Cannot read property 'dispatch' of undefined" randomly thrown in runs
我有一個集成測試,它依賴於我提供給帶有存根的測試平台的 2 個服務。
當我在此類別的訂閱塊中測試函數updateCategory()
,我有一個函數 ngRedux.dispatch({type: something})
錯誤:類型錯誤: TypeError: Cannot read property 'dispatch' of undefined
被隨機拋出,即使服務被存根並提供了函數。 出於某種奇怪的原因,它認為這是服務的屬性。
拋出此錯誤,無需對測試進行任何更改,只需刷新 karma 頁面:
它是如此不可預測,對我來說根本沒有意義。
測試床配置:
describe('AdminCategoriesComponent', () => {
let component: AdminCategoriesComponent;
let fixture: ComponentFixture<AdminCategoriesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
MatSnackBarModule,
ReactiveFormsModule,
FormsModule,
MatInputModule,
MatExpansionModule,
BrowserAnimationsModule,
NgReduxTestingModule
],
declarations: [AdminCategoriesComponent],
providers: [
{ provide: AdminService, useClass: AdminStub },
{ provide: NgRedux, useclass: MockNgRedux }
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents()
.then(() => {
MockNgRedux.reset();
fixture = TestBed.createComponent(AdminCategoriesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
}));
測試配置:
it('should update category', () => {
component.categoryID = 1;
component.categoryTitle = 'Test Category Title';
component.categoryDescription = 'Test Category Description';
component.ngOnInit();
fixture.detectChanges();
component.categoryForm.value.categoryTitle = 'New Category Title';
component.categoryForm.value.categoryDescription =
'New Category Description';
component.updateCategory();
fixture.detectChanges();
expect(component.localLoading).toBeFalsy();
});
如果沒有上面的測試——錯誤不會被拋出。 如果沒有該訂閱塊中的 dispatch 函數,也不會拋出錯誤。
angular-redux 模塊已經過時並且通常是垃圾,當您嘗試使用它運行任何測試時,這變得更加明顯。 在切換到 @ngrx/store 並正確學習如何使用 observable 一年后,解決方案是使用 @ngrx/store 或 fork angular-redux 並自己修復錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.