【发布时间】:2022-09-29 03:37:07
【问题描述】:
我正在使用 Jest/Testing Library 编写单元测试。
当我渲染一个使用 redux/toolkit 的 createEntityAdapter 方法的组件时,它返回这个错误:
TypeError: Cannot read property \'id\' of undefined
11 | companySelectors.selectAll,
12 | (selectedCompanyId, entities) => {
> 13 | return entities.find((e) => e.id === selectedCompanyId);
| ^
14 | },
15 | );
上面的代码是传入的 createSelector 参数的一部分。
这是选择器:
import { createSelector } from \'@reduxjs/toolkit\';
import { RootState } from \'src/store\';
import { companyAdapter } from \'./company.slice\';
export const companySelectors = companyAdapter.getSelectors<RootState>(
(state) => state.company,
);
export const getSelectedCompany = createSelector(
(state: RootState) => state.company.selectedId,
companySelectors.selectAll,
(selectedCompanyId, entities) => {
return entities.find((e) => e.id === selectedCompanyId);
},
);
这里是创建 companyAdapter 的地方:
import { createEntityAdapter, createSlice } from \'@reduxjs/toolkit\';
import { Company } from \'src/types/company\';
import { getAllCashScenarios } from \'../cash-scenario/cash-scenario.thunk\';
import {
getAllCompanies,
getAuthenticatedCompany,
getCurrentCompany,
} from \'./company.thunk\';
export interface CompanyState {
current: Company;
selectedId: string;
cashScenarios: number[];
}
export const companyAdapter = createEntityAdapter<Company>();
const initialState = companyAdapter.getInitialState({
current: undefined,
selectedId:
typeof window !== \'undefined\'
? window.localStorage.getItem(\'companyId\')
: undefined,
cashScenarios: [],
} as CompanyState);
export const slice = createSlice({
name: \'company\',
initialState,
reducers: {
selectCompany: (state, action) => {
state.selectedId = action.payload;
localStorage.setItem(\'companyId\', state.selectedId);
},
},
extraReducers: (builder) => {
builder.addCase(getCurrentCompany.fulfilled, (state, action) => {
state.current = action.payload;
});
builder.addCase(getAuthenticatedCompany.fulfilled, (state, action) => {
state.current = action.payload;
state.selectedId = state.current.id;
localStorage.setItem(\'companyId\', state.selectedId);
});
builder.addCase(getAllCompanies.fulfilled, (state, action) => {
companyAdapter.upsertMany(state, action);
});
builder.addCase(getAllCashScenarios.fulfilled, (state, action) => {
state.cashScenarios = action.payload.map((p) => p.id);
});
},
});
const { reducer } = slice;
export default reducer;
export const companyActions = slice.actions;
鉴于上面的代码,我如何确保 \'entities\' 对象中的各个实体不是未定义的?
当我渲染组件时,我在 Provider 中传入了一个模拟状态:
const mockState = company: {
ids: [\'1234\', \'1235\'],
entities: {
1234: {
id: \'1234\',
name: \'Awesome Company\',
createdDate: \'2021-01-01\',
lastUpdated: \'2022-01-03\',
dates: [\'Jan 2016\', \'Feb 2016\'],
}
},
selectedId: \'1234\',
}
显然,selectedId 和 entities 已定义。
-
嘿,你找到答案了吗?
标签: javascript reactjs redux react-redux redux-toolkit