首页 > 解决方案 > 业力错误:无法设置未定义的属性“beforePreactivation”

问题描述

我正在尝试在我的 Angular 5 应用程序中测试一个组件,该应用程序使用,并且在此选择器中未定义时@ngrx/router-store遇到问题:state

import * as fromRouter from '@ngrx/router-store';

export const selectRouter = (state: AppState) => state.router;

export const selectUrl = createSelector(
  selectRouter,
  (state: fromRouter.RouterReducerState<RouterStateUrl>) => state.state && state.state.url // <--- state here is undefined
);

为了克服这个问题,我尝试在我的 TestBed 生成的模块中添加以下导入:

imports: [
  RouterModule.forChild(wizardRoutes),
  StoreModule.forRoot(reducers, {metaReducers}),
  EffectsModule.forRoot([MyEffects, WizardEffects]),
  HttpClientModule,
  StoreRouterConnectingModule.forRoot() // <--- this makes it happier
]

但是,现在我在 Karma 测试浏览器窗口中收到以下错误:

TypeError:无法在 StoreRouterConnectingModule.webpackJsonp../node_modules/@ngrx/router-store/@ngrx/router-store.es5.js.StoreRouterConnectingModule.setUpBeforePreactivationHook (http://localhost:9878/_karma_webpack_ /webpack:/node_modules/@ngrx/router-store/@ngrx/router-store.es5.js:169:1 )

官方文档中关于测试路由器商店的信息很少或根本没有,我在谷歌上也找不到任何东西。

我知道我没有提供大量代码,所以请让我知道您还需要查看什么,我会添加它。

标签: angularunit-testingkarma-jasminengrxngrx-router-store

解决方案


要连接Router,您需要导入路由器 viaforRoot而不是forChild.

事实上,你必须导入StoreRouterConnectingModule.forRoot才能使用 NgRx 的路由器减速器。

尝试使用:

imports: [
  RouterModule.forRoot(wizardRoutes),
  StoreModule.forRoot(reducers, {metaReducers}),
  EffectsModule.forRoot([MyEffects, WizardEffects]),
  HttpClientModule,
  StoreRouterConnectingModule.forRoot()
]

推荐阅读