我使用 Reselect 库创建了一个简单的 Redux 选择器。选择器获取数组中的最后一个对象。
在Reselect docs中,测试示例是使用 Assert 库而不是 Expect 库构建的,但我的应用程序源自 React Create App,因此我包含了 Expect 和 Jest。
无论如何,无论我如何编写选择器测试,它都会挂在嵌套的 reducer: 上TypeError: Cannot read property 'arrayOfObj' of undefined
。
选择器.js
import { createSelector } from 'reselect'
const getArrayOfObj = (state) => state.reducer1.arrayOfObj
export const getLastObj = createSelector(
[ getArrayOfObj ],
(arrayOfObj) => {
return arrayOfObj[arrayOfObj.length-1]
}
)
选择器.test.js
import * as selectors from 'Selectors'
const mockState = {
reducer1: {
arrayOfObj: [
{id: 1},
{id: 2},
{id: 3},
{id: 4},
],
...
},
reducer2: {
...
}
}
describe('selectors', () => {
it('getLastObj should get last obj in array', () => {
expect(selectors.getLastObj(mockState)).toDeepEqual({id: 4});
});
});