使用笑话和酶对 useReducer 钩子进行单元测试

时间:2021-07-28 18:30:46

标签: reactjs unit-testing jestjs react-hooks enzyme

我有如下代码:

export default function func() {
  const [state, setState] = useReducer(
   (state, newState) => ({...state, ...newState}),
   {loading: false, name: ""}
  );

  if(state.loading) {
    return <Loader />
  }
  return (
    <div>{state.name}</div>  
  );
}

我一直在谷歌搜索这个,但没有找到预期的结果。 那么为此组件编写单元测试的最佳方法是什么?

提前致谢

1 个答案:

答案 0 :(得分:1)

最好的方法是将您的 reducer 提取到一个单独的可测试函数中,如下所示:

export default function func() {
  const [state, setState] = useReducer(reducer, {
    loading: false,
    name: ""
  });

  if (state.loading) {
    return <Loader />;
  }
  return (
    <div>{ state.name }</div>
  );
}

export const reducer = (state, newState) => ({
  ...state,
  ...newState,
})

此外,当使用 reducer 模式时,您的第二个参数通常是描述某个操作的“动作”。 Here's an article describing this pattern in depth