【发布时间】:2020-04-04 02:59:17
【问题描述】:
减速机
// src/reducers/FooReducer.js
export function FooReducer(state, action) {
switch (action.type) {
case 'update': {
return action.newState;
}
// ... other actions
default:
throw new Error('Unknown action type');
}
}
组件
// src/components/BarComponent.js
export function BarComponent() {
const [state, dispatch] = useReducer(FooReducer, []);
return (
{state.map((item) => (<div />))}
);
}
测试
// src/components/BarComponent.test.js
it('should render as many divs as there are items', () => {
act(() => {
const { result } = renderHook(() => useReducer(FooReducer, [1]));
const [, dispatch] = result.current;
wrapper = mount(<BarComponent />);
dispatch({type: 'update', newState: [1, 2, 3]});
});
expect(wrapper.find(div)).toHaveLength(3);
});
上面的测试示例不起作用,但用于演示我想要实现的目标。并且实际上会渲染 0 个 div,因为组件中声明的初始状态包含 0 个项目。
-
为了测试目的,我将如何修改 reducer 的状态或更改其部署的 initialState?
-
我习惯于 Redux reducer 在多个组件中使用,但是 useReducer 需要一个传递的 initialState... 这引发了一个问题:react-hook 的 reducer 是否可以作为单个实例通过多个组件使用,或者它始终是 2 个单独的实例?
【问题讨论】:
标签: reactjs react-hooks enzyme react-hooks-testing-library