如何测试 ngrx 路由器存储选择器
How to test ngrx router store selector
在我们的应用程序中,我们有一个简单的商店,在根级别包含一个 AuthState
和一个 RouterState
。 RouterState
是通过 @ngrx/router-store
方法创建的。
我们有一些选择器必须使用 RouterState 来检索参数,例如将其与其他选择器结果组合。
我们的问题是我们无法找到一种方法来正确设置测试套件以测试此类组合选择器。
减速器设置
应用程序模块导入
StoreModule.forRoot(reducers, { metaReducers }),
StoreRouterConnectingModule.forRoot({
stateKey: 'router',
}),
StoreDevtoolsModule.instrument(),
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;
}
);
这是 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
)
测试设置
@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);
});
测试及其结果
测试 1
it('should retrieve routerState', () => {
router.navigateByUrl('/list/123');
store.select(getRouterState).subscribe(routerState => console.log(routerState));
});
{ router:
{ state: { url: '/list/123', params: {someId: 123}, queryParams: {} },
navigationId: 1 },
auth:
{ loggedIn: false } }
如您所见,getRouterState
选择器不仅检索状态的 router
部分,还检索包含整个 routerState
+ [=27 的 object =] State
。 router 和 auth 是这个 object 的 children。所以选择器无法检索到正确的切片。
测试 2
it('should retrieve routerStateUrl', () => {
router.navigateByUrl('/list/123');
store.select(getRouterStateUrl).subscribe(value => console.log(value));
});
undefined - TypeError: Cannot read property 'state' of undefined
测试 3
it('should retrieve mixed selector results', () => {
router.navigateByUrl('/list/123');
store.select(getMixedSelection).subscribe(value => console.log(value));
});
undefined
TypeError: Cannot read property 'state' of undefined
TypeError: Cannot read property 'loggedIn' of {auth: {}, router: {}}
备注
请注意语法
StoreModule.forRoot({
// How to add auth at that level
router: combineReducers(reducers)
}),
如果我们想使用多个 reducer 组合选择器,这似乎是强制性的。我们可以只使用 forRoot(reducers)
但我们不能只测试路由器选择器。州的其他部分将不存在。
例如,如果我们需要测试:
export const getMixedSelection = createSelector(
isSomeIdParamValid,
getIsLoggedIn,
(paramValid, isLoggedIn) => paramValid && isLoggedIn
)
我们需要路由器和身份验证。而且我们找不到合适的测试设置来让我们使用 AuthState
和 RouterState
.
来测试这样的组合选择器
问题
如何设置此测试以便我们基本上可以测试我们的选择器?
当我们 运行 应用程序时,它运行完美。所以问题只出在测试设置上。
我们认为使用真实路由器设置测试台可能是错误的想法。但是我们很难(仅)模拟 routerSelector 并给它一个模拟的路由器状态切片,仅用于测试目的。
仅模拟这些路由器选择器真的很难。监视 store.select
很容易,但监视 store.select(routerSelectorMethod)
,方法作为参数变得一团糟。
我自己也在努力解决这个问题,routerState 的 'state' 属性 未定义。我发现对我有用的解决方案是调用 router.initialNavigation() 来启动 RouterTestingModule,后者又会设置路由器存储。
在我的例子中,我需要测试一个 CanActivate 守卫,它同时使用根存储选择器和特征存储选择器。下面的测试模块设置适用于我:
describe('My guard', () => {
let myGuard: MyGuard;
let router: Router;
let store: Store<State>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'one',
component: MockTestComponent
},
{
path: 'two',
component: MockTestComponent
}
]),
StoreModule.forRoot({
...fromRoot.reducers,
'myFeature': combineReducers(fromFeature.reducers)
}),
StoreRouterConnectingModule.forRoot({
stateKey: 'router', // name of reducer key
}),
],
declarations: [MockTestComponent],
providers: [MyGuard, {provide: RouterStateSerializer, useClass: CustomSerializer}]
}).compileComponents();
myGuard = TestBed.get(MyGuard);
router = TestBed.get(Router);
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
router.initialNavigation();
}));
});
现在您可以使用 projector
属性:
模拟选择器依赖项
我的-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
);
我的-reducer.spec.ts
import * as fromMyReducers from './my-reducers';
describe('My Selectors', () => {
it('should calc selectTotal', () => {
expect(fromMyReducers.selectTotal.projector(2, 3)).toBe(5);
});
});
在我们的应用程序中,我们有一个简单的商店,在根级别包含一个 AuthState
和一个 RouterState
。 RouterState
是通过 @ngrx/router-store
方法创建的。
我们有一些选择器必须使用 RouterState 来检索参数,例如将其与其他选择器结果组合。
我们的问题是我们无法找到一种方法来正确设置测试套件以测试此类组合选择器。
减速器设置
应用程序模块导入
StoreModule.forRoot(reducers, { metaReducers }),
StoreRouterConnectingModule.forRoot({
stateKey: 'router',
}),
StoreDevtoolsModule.instrument(),
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;
}
);
这是 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
)
测试设置
@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);
});
测试及其结果
测试 1
it('should retrieve routerState', () => {
router.navigateByUrl('/list/123');
store.select(getRouterState).subscribe(routerState => console.log(routerState));
});
{ router: { state: { url: '/list/123', params: {someId: 123}, queryParams: {} }, navigationId: 1 }, auth: { loggedIn: false } }
如您所见,getRouterState
选择器不仅检索状态的 router
部分,还检索包含整个 routerState
+ [=27 的 object =] State
。 router 和 auth 是这个 object 的 children。所以选择器无法检索到正确的切片。
测试 2
it('should retrieve routerStateUrl', () => {
router.navigateByUrl('/list/123');
store.select(getRouterStateUrl).subscribe(value => console.log(value));
});
undefined - TypeError: Cannot read property 'state' of undefined
测试 3
it('should retrieve mixed selector results', () => {
router.navigateByUrl('/list/123');
store.select(getMixedSelection).subscribe(value => console.log(value));
});
undefined
TypeError: Cannot read property 'state' of undefined
TypeError: Cannot read property 'loggedIn' of {auth: {}, router: {}}
备注
请注意语法
StoreModule.forRoot({
// How to add auth at that level
router: combineReducers(reducers)
}),
如果我们想使用多个 reducer 组合选择器,这似乎是强制性的。我们可以只使用 forRoot(reducers)
但我们不能只测试路由器选择器。州的其他部分将不存在。
例如,如果我们需要测试:
export const getMixedSelection = createSelector(
isSomeIdParamValid,
getIsLoggedIn,
(paramValid, isLoggedIn) => paramValid && isLoggedIn
)
我们需要路由器和身份验证。而且我们找不到合适的测试设置来让我们使用 AuthState
和 RouterState
.
问题
如何设置此测试以便我们基本上可以测试我们的选择器?
当我们 运行 应用程序时,它运行完美。所以问题只出在测试设置上。
我们认为使用真实路由器设置测试台可能是错误的想法。但是我们很难(仅)模拟 routerSelector 并给它一个模拟的路由器状态切片,仅用于测试目的。
仅模拟这些路由器选择器真的很难。监视 store.select
很容易,但监视 store.select(routerSelectorMethod)
,方法作为参数变得一团糟。
我自己也在努力解决这个问题,routerState 的 'state' 属性 未定义。我发现对我有用的解决方案是调用 router.initialNavigation() 来启动 RouterTestingModule,后者又会设置路由器存储。
在我的例子中,我需要测试一个 CanActivate 守卫,它同时使用根存储选择器和特征存储选择器。下面的测试模块设置适用于我:
describe('My guard', () => {
let myGuard: MyGuard;
let router: Router;
let store: Store<State>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'one',
component: MockTestComponent
},
{
path: 'two',
component: MockTestComponent
}
]),
StoreModule.forRoot({
...fromRoot.reducers,
'myFeature': combineReducers(fromFeature.reducers)
}),
StoreRouterConnectingModule.forRoot({
stateKey: 'router', // name of reducer key
}),
],
declarations: [MockTestComponent],
providers: [MyGuard, {provide: RouterStateSerializer, useClass: CustomSerializer}]
}).compileComponents();
myGuard = TestBed.get(MyGuard);
router = TestBed.get(Router);
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
router.initialNavigation();
}));
});
现在您可以使用 projector
属性:
我的-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
);
我的-reducer.spec.ts
import * as fromMyReducers from './my-reducers';
describe('My Selectors', () => {
it('should calc selectTotal', () => {
expect(fromMyReducers.selectTotal.projector(2, 3)).toBe(5);
});
});