如何测试 ngrx 路由器存储选择器

Bla*_*axy 5 ngrx angular ngrx-router-store

在我们的应用程序中,我们有一个简单的商店,在根级别包含 anAuthState和 a RouterState。它RouterState是通过@ngrx/router-store方法创建的。

我们有一些选择器必须使用 RouterState 来检索例如参数,然后将其与其他选择器结果组合。

我们的问题是我们无法设法找到一种方法来正确设置测试套件以便能够测试此类组合选择器。

减速机设置

应用程序模块导入

StoreModule.forRoot(reducers, { metaReducers }),
StoreRouterConnectingModule.forRoot({
  stateKey: 'router',
}),
StoreDevtoolsModule.instrument(),
Run Code Online (Sandbox Code Playgroud)

reducers存在以下情况:

减速机

export interface RouterStateUrl {
  url: string;
  queryParams: Params;
  params: Params;
}

export interface State {
  router: fromNgrxRouter.RouterReducerState<RouterStateUrl>;
  auth: fromAuth.AuthState;
}

export const reducers: ActionReducerMap<State> = {
  router: fromNgrxRouter.routerReducer,
  auth: fromAuth.reducer,
};

export const getRouterState = createFeatureSelector<fromNgrxRouter.RouterReducerState<RouterStateUrl>>('router');

export const getRouterStateUrl = createSelector(
  getRouterState,
  (routerState: fromNgrxRouter.RouterReducerState<RouterStateUrl>) => routerState.state
);

export const isSomeIdParamValid = createSelector(
  getRouterState,
  (routerS) => {
    return routerS.state.params && routerS.state.params.someId;
  }
);
Run Code Online (Sandbox Code Playgroud)

这是 AuthState 减速器:

export interface AuthState {
  loggedIn: boolean;
}

export const initialState: AuthState = {
  loggedIn: false,
};

export function reducer(
  state = initialState,
  action: Action
): AuthState {
  switch (action.type) {
    default: {
      return state;
    }
  }
}

export const getAuthState = createFeatureSelector<AuthState>('auth');
export const getIsLoggedIn = createSelector(
  getAuthState,
  (authState: AuthState) => {
    return authState.loggedIn;
  }
);

export const getMixedSelection = createSelector(
  isSomeIdParamValid,
  getIsLoggedIn,
  (paramValid, isLoggedIn) => paramValid && isLoggedIn
)
Run Code Online (Sandbox Code Playgroud)

测试设置

@Component({
  template: ``
})
class ListMockComponent {}

describe('Router Selectors', () => {
  let store: Store<State>;
  let router: Router;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([{
          path: 'list/:someId',
          component: ListMockComponent
        }]),
        StoreModule.forRoot({
          // How to add auth at that level
          router: combineReducers(reducers)
        }),
        StoreRouterConnectingModule.forRoot({
          stateKey: 'router',
        }),
      ],
      declarations: [ListMockComponent],
    });

    store = TestBed.get(Store);
    router = TestBed.get(Router);
  });
Run Code Online (Sandbox Code Playgroud)

测试及其结果

测试1

it('should retrieve routerState', () => {
  router.navigateByUrl('/list/123');
  store.select(getRouterState).subscribe(routerState => console.log(routerState));
});
Run Code Online (Sandbox Code Playgroud)

{ 路由器:{ 状态:{ url:'/list/123',参数:{someId:123},queryParams:{} },navigationId:1 },auth:{登录:false } }

正如您所看到的,getRouterState选择器不仅仅检索router状态的切片,而是包含整个routerState+的对象authState State。router 和 auth 是该对象的子对象。因此选择器无法检索正确的切片。

测试2

it('should retrieve routerStateUrl', () => {
  router.navigateByUrl('/list/123');
  store.select(getRouterStateUrl).subscribe(value => console.log(value));
});
Run Code Online (Sandbox Code Playgroud)

未定义 - 类型错误:无法读取未定义的属性“状态”

测试3

it('should retrieve mixed selector results', () => {
  router.navigateByUrl('/list/123');
  store.select(getMixedSelection).subscribe(value => console.log(value));
});
Run Code Online (Sandbox Code Playgroud)

不明确的

类型错误:无法读取未定义的属性“状态”

类型错误:无法读取 {auth: {},路由器:{}} 的属性“loggedIn”

笔记

请注意语法

StoreModule.forRoot({
  // How to add auth at that level
  router: combineReducers(reducers)
}),
Run Code Online (Sandbox Code Playgroud)

如果我们想使用多个减速器组合选择器,这似乎是强制性的。我们可以只使用forRoot(reducers),但我们不能只测试路由器选择器。该州的其他部分将不存在。

例如,如果我们需要测试:

export const getMixedSelection = createSelector(
  isSomeIdParamValid,
  getIsLoggedIn,
  (paramValid, isLoggedIn) => paramValid && isLoggedIn
)
Run Code Online (Sandbox Code Playgroud)

我们需要路由器和身份验证。我们找不到合适的测试设置来允许我们使用AuthState和测试这样的组合选择器RouterState

问题

如何设置此测试以便我们可以基本测试我们的选择器?

当我们运行该应用程序时,它运行得很好。所以问题仅在于测试设置。

我们认为使用真实路由器设置测试床可能是一个错误的想法。但是我们很难(仅)模拟 routerSelector 并为其提供一个模拟的路由器状态切片,仅用于测试目的。

仅模拟这些路由器选择器确实很难。监视store.select很容易,但监视store.select(routerSelectorMethod),用方法作为论证就变得一团糟。

Mik*_*nov 1

现在您可以使用projector属性模拟选择器依赖关系:

my-reducer.ts

export interface State {
  evenNums: number[];
  oddNums: number[];
}

export const selectSumEvenNums = createSelector(
  (state: State) => state.evenNums,
  (evenNums) => evenNums.reduce((prev, curr) => prev + curr)
);
export const selectSumOddNums = createSelector(
  (state: State) => state.oddNums,
  (oddNums) => oddNums.reduce((prev, curr) => prev + curr)
);
export const selectTotal = createSelector(
  selectSumEvenNums,
  selectSumOddNums,
  (evenSum, oddSum) => evenSum + oddSum
);
Run Code Online (Sandbox Code Playgroud)

my-reducer.spec.ts

import * as fromMyReducers from './my-reducers';

describe('My Selectors', () => {

  it('should calc selectTotal', () => {
    expect(fromMyReducers.selectTotal.projector(2, 3)).toBe(5);
  });

});
Run Code Online (Sandbox Code Playgroud)

摘自官方文档